Ogrish Man Ogrish Man - 1 year ago 153
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
is nil and
defer resp.Body.Close()
. What's the correct order to do these two operations?

Answer Source

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()
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download