我试图通过仅在看到正确的 content-type 和 content-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 值?
什么是最好的策略?
最佳答案
如果应用程序不想读取它,应用程序应该关闭响应主体。在最新版本的 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。
在所有情况下,当应用程序完成响应时关闭响应主体。
不能保证对 HEAD 请求的响应包含 Content-Length header 。
关于http - 从请求中获取响应是否会获取所有内容? (golang, 网络/http),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38195991/