英文:
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.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论