In the following code is it also necessary to close the response body in the error case:
res, err := http.Get(url)
if err != nil {
log.Printf("Error: %s\n", err)
}
defer res.Body.Close()
In the following code is it also necessary to close the response body in the error case:
res, err := http.Get(url)
if err != nil {
log.Printf("Error: %s\n", err)
}
defer res.Body.Close()
General concept is that when a function (or method) has multi return values one being an
error
, error should be checked first and only proceed if the error isnil
. Functions should return zero values for other (non-error) values if there is anerror
. If the function behaves differently, it should be documented.http.Get()
does not document such deviation.So it should be handled like this:
Notes:
As JimB confirms too, if a non-
nil
error is returned, even if the response is non-nil
, we don't have to close it. In case of a redirection error the non-nil
response may hold context and further information about where following the redirect failed. See details below:http.Get()
honors the general concept "most of the time": it returnsnil
response if there is an error:However checking
client.go
, unexported methodClient.doFollowingRedirects()
, currently line #427:So due to a backward compatibility issue it may return a non-
nil
response and a non-nil
error at the same time, if redirection fails.On the other hand trying to call
resp.Body.Close()
ifresp
isnil
will cause a run-time panic.So if we want to close response body in this case, it could look like this (can only be closed if
resp
is notnil
):Or:
The doc of
http.Response
guarantees thatResponse.Body
will not benil
even if there is no response data:But if the error is not
nil
, you don't have to close the non-nil
response body.