我有一個奇怪的情況。我想application/json; charset=utf-8從 http 處理程序返回內(nèi)容類型。func handleTest() http.HandlerFunc { return func(w http.ResponseWriter, r *http.Request) { if r.Header.Get("Accept") != "application/json" { w.WriteHeader(http.StatusNotAcceptable) return } w.WriteHeader(http.StatusOK) w.Header().Set("Content-Type", "application/json; charset=utf-8") json.NewEncoder(w).Encode(map[string]string{"foo": "bar"}) }}當我在單元測試中檢查這一點時,它是正確的。這個測試沒有失敗。func TestTestHandler(t *testing.T) { request, _ := http.NewRequest(http.MethodGet, "/test", nil) request.Header.Set("Accept", "application/json") response := httptest.NewRecorder() handleTest().ServeHTTP(response, request) contentType := response.Header().Get("Content-Type") if contentType != "application/json; charset=utf-8" { t.Errorf("Expected Content-Type to be application/json; charset=utf-8, got %s", contentType) return }}但是當我嘗試使用 curl (和其他客戶端)時,它會顯示為text/plain; charset=utf-8.$ curl -H 'Accept: application/json' localhost:8080/test -v* Trying 127.0.0.1:8080...* TCP_NODELAY set* Connected to localhost (127.0.0.1) port 8080 (#0)> GET /test HTTP/1.1> Host: localhost:8080> User-Agent: curl/7.68.0> Accept: application/json> * Mark bundle as not supporting multiuse< HTTP/1.1 200 OK< Date: Tue, 28 Dec 2021 13:02:27 GMT< Content-Length: 14< Content-Type: text/plain; charset=utf-8< {"foo":"bar"}* Connection #0 to host localhost left intact我用 curl、insomnia 和 python 試過這個。在所有 3 種情況下,內(nèi)容類型都是text/plain; charset=utf-8.是什么導致了這個問題,我該如何解決?
1 回答

溫溫醬
TA貢獻1752條經(jīng)驗 獲得超4個贊
從http 包文檔:
WriteHeader 發(fā)送帶有提供的狀態(tài)代碼的 HTTP 響應標頭。
和
在調(diào)用 WriteHeader(或 Write)之后更改標頭映射無效,除非修改的標頭是預告片。
因此,您在標頭已發(fā)送到客戶端之后設(shè)置“Content-Type”標頭。WriteHeader
雖然模擬這可能有效,因為可以在調(diào)用后修改存儲標頭的緩沖區(qū)。但是當實際使用 TCP 連接時,您不能這樣做。
所以只需移動你的w.WriteHeader(http.StatusOK)
,這樣它就會在之后發(fā)生w.Header().Set(...)
- 1 回答
- 0 關(guān)注
- 85 瀏覽
添加回答
舉報
0/150
提交
取消