从请求中获取响应是否会获取所有内容? (戈朗,net/http)

Does getting Response from Request get all of the body? (golang, net/http)

我试图通过仅在看到正确的 content-typecontent-length 较小时才读取 http 响应正文来避免浪费流量比设定的阈值。

httpRequest, err := http.NewRequest("GET", url, nil)
httpResponse, err := httpClient.Do(httpRequest)
contentType := httpResponse.Header.Get("Content-Type")

// ... check for correct contentType    

// Read body into memory?
content, err := ioutil.ReadAll(httpResponse.Body)

是否正确假设如果我发出 GET 请求,无论我是否调用最后一行,我都将获得所有正文 iotuil.ReadAll(httpResponse.Body) 还是不?

如果是这样,我能想到的避免浪费流量的唯一方法是使用 HEAD 请求,但如果我真的想阅读正文,我将不得不发出另一个 GET 请求。如果我发出 HEAD 请求,我也会得到正确的 content-length 值吗?

最好的策略是什么?

如果应用程序不想读取响应,则应关闭响应 body。在最新版本的 Go 中,net/http client will close the underlying network connection instead of slurping up the remainder of the response body from the network.

Content-Length header 可能没有设置。在这种情况下,应用程序应该读取到阈值字节数或 EOF。

在所有情况下,在应用程序完成响应后关闭响应 body。

无法保证对 HEAD 请求的响应包含 Content-Length header。