http - 从请求中获取响应是否会获取所有内容? (golang, 网络/http)

标签 http go web-crawler

我试图通过仅在看到正确的 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 值?

什么是最好的策略?

最佳答案

如果应用程序不想读取它,应用程序应该关闭响应主体。在最新版本的 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/

相关文章:

file - 上传多个文件,enctype =“multipart/form-data”

csv - 为什么这会给我一个未定义的错误?

MP3链接爬虫

google-app-engine - 找不到包 "appengine/cloudsql"

javascript - Selenium 与 PhantomJS : Form being validated but not submitted

web-scraping - Scrapy - 解析给定域的所有子页面

http - 域的cookies被发送到子域,如何解决?

http - 在golang中测试http.Pusher和推送功能

c - 如何从 GET HTTP 请求中仅获取消息正文?

go - go get命令做缓存吗?