Go http.Get 是必须要 close response body

Go 里有个很奇怪的设计是 http.Get 或者 http.Post 的回包 resp 是必须要手动调用 resp.Body.Close() 的。

如果需要读取 Body 数据，那么 Close 是正常的，如果根本不需要判断 resp ，为什么需要 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.

也有人在 Stackoverflow 上问了类似的问题：is resp.Body.Close() necessary if we don't read anything from the body?


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.

简单来讲就是：为了提高效率，http.Get 等请求的 TCP 连接是不会关闭的（再次向同一个域名请求时，复用连接），所以必须要手动关闭。

2019-01-24 10:43:32 更新

不管是否使用 Resp 的内容都需要手动关闭，否则会导致进程打开的 fd 一直变多，最终系统杀掉进程，报错类似： http: Accept error: accept tcp [::]:4200: accept4: too many open files; retrying in 1s

Date: 2018-12-06 19:34

Author: JerryZhang