RuslanN RuslanN - 1 year ago 93
HTTP Question

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

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()

Answer Source

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

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download