当前位置: > > > > golng 获取 url 并 resp.Body.Close()
golng 获取 url 并 resp.Body.Close()
来源:stackoverflow
2024-04-25 15:15:38
0浏览
收藏
“纵有疾风来,人生不言弃”,这句话送给正在学习Golang的朋友们,也希望在阅读本文《golng 获取 url 并 resp.Body.Close()》后,能够真的帮助到大家。我也会在后续的文章中,陆续更新Golang相关的技术文章,有好的建议欢迎大家在评论留言,非常感谢!
问题内容
我正在寻找 go 代码来获取 url,在大多数情况下,这是用于在 go 上获取 url 的代码:
func main() {
for _, url := range os.Args[1:] {
resp, err := http.Get(url)
if err != nil {
fmt.Fprintf(os.Stderr, "fetch: %v\n", err)
os.Exit(1)
}
b, err := ioutil.ReadAll(resp.Body)
resp.Body.Close()
if err != nil {
fmt.Fprintf(os.Stderr, "fetch: reading %s: %v\n", url, err)
os.Exit(1)
}
fmt.Printf("%s", b)
}
}
我的问题为什么需要这里 resp.body.close() 以及这到底是做什么的?
解决方案
如果您深入研究 http 文档
用于生成响应的 get 方法是 response
func (c *client) get(url string) (resp *response, err error)
在响应源中:
// Body represents the response body.
//
// The response body is streamed on demand as the Body field
// is read. If the network connection fails or the server
// terminates the response, Body.Read calls return an error.
//
// The http Client and Transport guarantee that Body is always
// non-nil, even on responses without a body or responses with
// a zero-length body. It is the caller's responsibility to
// close Body. The default HTTP client's Transport may not
// reuse HTTP/1.x "keep-alive" TCP connections if the Body is
// not read to completion and closed.
//
// The Body is automatically dechunked if the server replied
// with a "chunked" Transfer-Encoding.
Body io.ReadCloser
因此 close() 整理了用于获取 body 的资源
如果不这样做,响应(resp)将无法“保持活动”,我猜响应中的某些资源有可能无法回收
以上就是《golng 获取 url 并 resp.Body.Close()》的详细内容,更多关于的资料请关注米云公众号!
