Is it enough to use blank identifier for http.Response to prevent memory leaks in Golang?

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

Is it enough to use blank identifier for http.Response to prevent memory leaks in Golang?

问题

例如,我正在进行一个POST请求,而且我根本不需要响应对象。

_, err := http.Post(url, "", &buf)

在这种情况下,我是否不会发生内存泄漏?响应的Body会被正确地清空以便进行连接重用吗?还是我需要像通常那样使用defer resp.Body.Close()来关闭它?

英文:

For example, I am making a post request and I don't need the response object at all.

_, err := http.Post(url, "", &buf)

Am I safe from memory leak in that case? Will the response.Body be drained for proper connection reuse? Or I need to do the usual defer resp.Body.Close() thing?

答案1

得分: 5

应用程序必须关闭响应体以回收底层网络连接使用的资源。为了启用底层连接的重用,应用程序在关闭之前必须读取响应体。

将响应分配给空白标识符不会关闭连接。

对于赋值操作,包括对空白标识符的赋值,没有任何副作用。

playground示例

英文:

The application must close the response body to reclaim the resources used by the underlying network connection. To enable reuse of the underlying connection, the application must read the response body before closing.

Assigning the response to the blank identifier will not close the connection.

There are no side effects for assignments, including assignments to the blank identifier.

playground example

huangapple
  • 本文由 发表于 2016年11月15日 09:09:28
  • 转载请务必保留本文链接:https://go.coder-hub.com/40600463.html
匿名

发表评论

匿名网友

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

确定