我们编写了一个服务,该服务将一些编码数据作为块发送到代理服务,该代理服务需要设置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服务器。任何想法如何将标头作为响应的一部分。
答案 0 :(得分:1)
删除顶部的WriteHeader
呼叫。您只能将标头写入响应一次。致电WriteHeader
后,您将无法再设置标题。
Per the ResponseWriter documentation:
// 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.