我們編寫了一個服務,它將一些編碼數據分塊發送到需要設置 Content-Length 標頭的代理服務,以便它可以向端點發送正確的響應。即使我設置了 Content-Length 標頭,它仍然會作為對客戶端的響應的一部分被剝離。下面是設置標題的代碼func HTTPSuccessResponse(rw http.ResponseWriter, bufferLen int, media []byte) { rw.WriteHeader(http.StatusOK) rw.Header().Set("Content-Type", "opus/ogg; audio/ogg; codec=opus") length := strconv.Itoa(len(media)); rw.Header().Set("Content-Length", length) rw.Write(media)}下面是我嘗試使用 curl 請求時得到的響應bash-4.2# curl -v -X GET -k -H -i 'http://127.0.0.1:8090/preview'* About to connect() to 127.0.0.1 port 8090 (#0)* Trying 127.0.0.1...* Connected to 127.0.0.1 (127.0.0.1) port 8090 (#0)> GET /preview HTTP/1.1> User-Agent: curl/7.29.0> Host: 127.0.0.1:8090> Accept: */*>< HTTP/1.1 200 OK< Date: Tue, 14 May 2019 13:08:20 GMT< Content-Type: text/plain; charset=utf-8< Transfer-Encoding: chunked<我正在使用 Gorrila Mux 庫來設置 HTTP 服務器。關于如何將標頭作為響應的一部分的任何想法。
1 回答

www說
TA貢獻1775條經驗 獲得超8個贊
刪除WriteHeader
頂部的呼叫。您只能將標頭寫入響應一次。通話后,WriteHeader
您無法再設置任何標題。
根據 ResponseWriter 文檔:
? ? // Changing the header map after a call to WriteHeader (or
? ? // Write) has no effect unless the modified headers are
? ? // trailers.
所以你不能先調用它;但您也根本不需要調用它 - 來自相同的文檔:
? ? // If WriteHeader is not called explicitly, the first call to Write
? ? // will trigger an implicit WriteHeader(http.StatusOK).
? ? // Thus explicit calls to WriteHeader are mainly used to
? ? // send error codes.
- 1 回答
- 0 關注
- 115 瀏覽
添加回答
舉報
0/150
提交
取消