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?
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?
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()