亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

使用 httptest 和 curl 的不同內容類型

使用 httptest 和 curl 的不同內容類型

Go
慕姐8265434 2023-06-05 19:26:30
我正在嘗試這個 Go 代碼package mainimport (    "github.com/gorilla/mux"    "io"    "log"    "net/http")func HealthCheckHandler(w http.ResponseWriter, r *http.Request) {    w.WriteHeader(http.StatusOK)    w.Header().Set("Content-Type", "application/json")    io.WriteString(w, `{"alive": true}`)}func main() {    router := mux.NewRouter()    router.HandleFunc("/health", HealthCheckHandler).Methods("GET")    log.Printf("running server ...")    log.Fatal(http.ListenAndServe(":8000", router))}通過這個測試package mainimport (    "net/http"    "net/http/httptest"    "testing")func TestHealthCheckHandler(t *testing.T) {    req, err := http.NewRequest("GET", "/health", nil)    if err != nil {        t.Fatal(err)    }    rr := httptest.NewRecorder()    handler := http.HandlerFunc(HealthCheckHandler)    handler.ServeHTTP(rr, req)    if status := rr.Code; status != http.StatusOK {        t.Errorf("handler returned wrong status code: got %v want %v",            status, http.StatusOK)    }    t.Logf("%v", rr.Header())    if ctype := rr.Header().Get("Content-Type"); ctype != "application/json" {        t.Errorf("content type header does not match: got %v want %v",            ctype, "application/json")    }}當我運行測試時,一切正常go test -v=== RUN   TestHealthCheckHandler--- PASS: TestHealthCheckHandler (0.00s)    handlers_test.go:24: map[Content-Type:[application/json]]PASSok          0.012s是,但是當我運行該服務并用 curl 調用它時Content-Type,是application/jsonContent-Typetext/plaincurl -v localhost:8000/health*   Trying ::1...* Connected to localhost (::1) port 8000 (#0)> GET /health HTTP/1.1> Host: localhost:8000> User-Agent: curl/7.43.0> Accept: */*>< HTTP/1.1 200 OK< Date: Thu, 14 Feb 2019 01:37:15 GMT< Content-Length: 15< Content-Type: text/plain; charset=utf-8<* Connection #0 to host localhost left intact為什么行為不同于測試和執行?
查看完整描述

2 回答

?
MMMHUHU

TA貢獻1834條經驗 獲得超8個贊

問題是您在標題之前發送了身體。這在任何語言中都行不通——這是 HTTP 的事實,而不是 Go 的事實。


它沒有被您的測試捕獲的原因是您的測試實際上是在濫用ResponseRecorder;您在地圖中設置字段,然后直接從該地圖讀取字段。測試應該只檢查ResponseRecorder.Result,它旨在為您提供客戶端實際收到的結果,包括在發送正文時鎖定標頭:


if ctype := rr.Response().Header.Get("Content-Type"); ctype != "application/json" {

    t.Errorf("content type header does not match: got %v want %v",

        ctype, "application/json")

}


查看完整回答
反對 回復 2023-06-05
?
婷婷同學_

TA貢獻1844條經驗 獲得超8個贊

只需將您的功能更改為:


func HealthCheckHandler(w http.ResponseWriter, r *http.Request) {


    // this will cause a duplicate status header to be written

    // w.WriteHeader(http.StatusOK)


    w.Header().Set("Content-Type", "application/json")


    io.WriteString(w, `{"alive": true}`)

}


查看完整回答
反對 回復 2023-06-05
  • 2 回答
  • 0 關注
  • 159 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號