patterngoCritical
What could happen if I don't close response.Body?
Viewed 0 times
happenclosebodycoulddonresponsewhat
Problem
In Go, I have some http responses and I sometimes forget to call:
What happens in this case? will there be a memory leak? Also is it safe to put in
What if there is an error, could
resp.Body.Close()What happens in this case? will there be a memory leak? Also is it safe to put in
defer resp.Body.Close() immediately after getting the response object?client := http.DefaultClient
resp, err := client.Do(req)
defer resp.Body.Close()
if err != nil {
return nil, err
}What if there is an error, could
resp or resp.Body be nil?Solution
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.
From the
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.
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.
Code Snippets
client := http.DefaultClient
resp, err := client.Do(req)
if err != nil {
return nil, err
}
defer resp.Body.Close()Context
Stack Overflow Q#33238518, score: 197
Revisions (0)
No revisions yet.