英文:
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
应用程序必须关闭响应体以回收底层网络连接使用的资源。为了启用底层连接的重用,应用程序在关闭之前必须读取响应体。
将响应分配给空白标识符不会关闭连接。
对于赋值操作,包括对空白标识符的赋值,没有任何副作用。
英文:
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.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论