is resp.Body.Close() necessary if we don't read anything from the body?

huangapple go评论146阅读模式
英文:

is resp.Body.Close() necessary if we don't read anything from the body?

问题

我有一个函数,只是发送一个GET请求来检查状态码,不会读取任何响应体内容。我是否仍然需要在函数末尾加上resp.Body.Close()

当读取完响应体后,调用者应该关闭resp.Body。如果不关闭resp.Body,客户端的底层RoundTripper(通常是Transport)可能无法在后续的“keep-alive”请求中重用持久的TCP连接。

英文:

I have a function that just makes a get request to check the status code. It does not read anything from the body. Should I still end the function with resp.Body.Close() ?

> Callers should close resp.Body when done reading from it. If resp.Body is not closed, the Client's underlying RoundTripper (typically Transport) may not be able to re-use a persistent TCP connection to the server for a subsequent "keep-alive" request.

答案1

得分: 38

是的。当你调用http.Get时,该函数会在读取完所有HTTP头部后立即返回响应。响应的正文尚未被读取。Response.Body是对与服务器的网络连接的包装。当你从中读取时,它会下载响应的正文。

.Close()告诉系统你已经完成了网络连接。如果你没有读取响应正文,那么默认的http传输会关闭连接。(传输只能重用已读取正文的连接,因为如果它重用了一个未读取正文的连接,那么使用该连接进行的下一个请求将接收到上一个请求的响应!)

因此,如果你要进行多个请求,读取正文通常比仅仅Close()更高效,特别是对于相对昂贵的TLS连接。

如果你不需要响应的正文,你应该使用Head而不是Get。Head不需要读取或关闭响应正文。

英文:

Yes. When you call http.Get, the function returns a response as soon as all the HTTP headers have been read. The body of the response has not been read yet. The Response.Body is a wrapper around the network connection to the server. When you read from it, it downloads the body of the response.

.Close() tells the system that you're done with the network connection. If you have not read the response body, the default http transport closes the connection. (The transport can only re-use the connection if the body has been read, because if it reused a connection with an unread body the next request made using that connection would receive the previous request's response!)

So reading the Body is often more efficient than simply Close()ing if you're making more than one request - especially with TLS connections which are relatively expensive to create.

If you don't need the body of the response, you should use Head instead of Get. Head doesn't require reading or closing the response body.

huangapple
  • 本文由 发表于 2013年9月4日 02:06:57
  • 转载请务必保留本文链接:https://go.coder-hub.com/18598780.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定