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


i'm new go. if i'm doing http request let this:

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

now need check whether err nil , defer resp.body.close(). what's correct order these 2 operations?

you need check error right after call get. if get fails, resp set nil. means resp.body 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