2 回答

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")
}

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}`)
}
- 2 回答
- 0 關注
- 159 瀏覽
添加回答
舉報