Ogrish Man Ogrish Man - 3 months ago 8
HTTP Question

Golang - what's the correct order to check error and defer an operation?

I'm new to Go. If I'm doing an HTTP get request let this:

resp, err := http.Get("https://www.google.com")


Now I need to check whether
err
is nil and
defer resp.Body.Close()
. What's the correct order to do these two operations?

Answer

You need to check for error right after the call to Get. If Get fails, resp will be set to nil. This means that resp.Body would generate runtime nil pointer dereferenced error.

resp, err := http.Get("https://www.google.com")
if err != nil {
    // process error
    return err
}
defer resp.Body.Close()
Comments