4

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?

Just a learner
  • 26,690
  • 50
  • 155
  • 234
  • I don't think it makes a difference since the close call is deferred. It seems to be idiomatic to check the error first and then defer the close. – Sridhar Sep 02 '16 at 08:22
  • 2
    @Sridhar: This is **wrong**! if err!=nil then resp == nil in which case the defered Body.Close() will panic. – Volker Sep 02 '16 at 08:29
  • Yikes you're right - just tried it. Obviously never come across this because I handle all my errors straight away :) – Sridhar Sep 02 '16 at 08:38

1 Answers1

12

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()
abhink
  • 8,740
  • 1
  • 36
  • 48