What could happen if I don’t close response.Body?

What happens in this case? will there be a memory leak?

It’s a resource leak. The connection won’t be re-used, and can remain open in which case the file descriptor won’t be freed.

Also is it safe to put in defer resp.Body.Close() immediately after getting the response object?

No, follow the example provided in the documentation and close it immediately after checking the error.

client := http.DefaultClient
resp, err := client.Do(req)
if err != nil {
    return nil, err
}
defer resp.Body.Close()

From the http.Client documentation:

If the returned error is nil, the Response will contain a non-nil Body which the user is expected to close. If the Body is not both read to EOF and 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.

Leave a Comment