为什么在处理POST请求时,Go HTTP客户端会添加transfer-encoding=chunked头部?

huangapple go评论76阅读模式
英文:

Why go http client puts transfer-encoding=chunked header while processing POST

问题

我这样发送POST请求:

// ...填充非零的buf
req, _ := http.NewRequest("POST", url, bufio.NewReader(buf))
req.Header.Add("X-Uid", "12345")
req.Header.Add("Content-Length", strconv.Itoa(buf.Len()))

client := http.Client{}
resp, err := client.Do(req)

我期望不会传递"Transfer-Encoding"头,但是我在服务器日志中看到传递了"Transfer-Encoding: chunked"头。

英文:

I make POST request like so:

// ...pack non-zero buf
req, _ := http.NewRequest("POST", url, bufio.NewReader(buf))
req.Header.Add("X-Uid", "12345")
req.Header.Add("Content-Length", strconv.Itoa(buf.Len()))

client := http.Client{}
resp, err := client.Do(req)

I expect that no "Transfer-Encoding" header would be passed, but I see in server logs that "Transfer-Encoding: chunked" header is passed.

答案1

得分: 1

你正在将一个 bufio.Reader 传递给 HTTP 请求。由于无法确定 bufio.Reader 的长度,HTTP 包会覆盖 Content-Length 以确保请求有效。

如果你已经有了缓冲的内容,并且知道长度,就没有必要将其包装在 bufio.Reader 中,直接将缓冲区传递进去即可。如果你还没有缓冲的内容,可以允许它使用分块编码,在请求中不会产生任何功能上的差异。

英文:

You're passing a bufio.Reader to the http request. Since you can't determine the length of a bufio.Reader, the http package overrides the Content-Length to ensure the request is valid.

If you have the content buffered, and you know the length, there's no reason to wrap it in a bufio.Reader, just pass the buffer in directly. If you don't have the content buffered already, allow it to use chunked encoding which shouldn't make any functional difference in the request.

huangapple
  • 本文由 发表于 2017年8月28日 18:44:32
  • 转载请务必保留本文链接:https://go.coder-hub.com/45917169.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定