Should I error-check Close() on a response body?


The docs for net/http have the following example:

resp, err := http.Get("")
if err != nil {
defer resp.Body.Close()
body, err := ioutil.ReadAll(resp.Body)
fmt.Printf("%s", body)

Close returns an error, but it is not checked. Is there something I’m missing here? The importance of checking every error is frequently emphasized in go, but I see this defer resp.Body.Close() pattern a lot with no error checks.


There are two things to consider: What would you do with it if you checked it and there was an error? And, what would the side-effects be if there was an error?

In most cases, for closing a response body, the answer to both questions is… absolutely nothing. If there’s nothing you’d do if there was an error and the error has no appreciable impact, there’s no reason to check it.

Also note that Close() returns an error in order to fulfill the io.Closer interface; the function doesn’t necessarily return an error. You’d need to check the source to know for sure if it has an error case.

Answered By – Adrian

Answer Checked By – Timothy Miller (GoLangFix Admin)

Leave a Reply

Your email address will not be published.