登录
首页 >  Golang >  Go问答

设置 HTTP 响应中分块数据的 Content-Length

来源:stackoverflow

时间:2024-03-21 10:45:32 422浏览 收藏

在为代理服务发送分块数据时,需要在 HTTP 响应中设置 Content-Length 标头。尽管已设置该标头,但它仍然在对客户端的响应中被剥离。通过使用 Gorilla Mux 库设置 HTTP 服务器,解决方案是删除 writeheader 调用,因为调用 writeheader 后无法再设置任何标头。

问题内容

我们编写了一个服务,它将一些编码数据作为分块发送到代理服务,该代理服务需要设置 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 服务器。关于如何将标头作为响应的一部分的任何想法。


解决方案


删除顶部的 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.

以上就是《设置 HTTP 响应中分块数据的 Content-Length》的详细内容,更多关于的资料请关注golang学习网公众号!

声明:本文转载于:stackoverflow 如有侵犯,请联系study_golang@163.com删除
相关阅读
更多>
最新阅读
更多>
课程推荐
更多>