When to defer in Go

Tony Choe
Apr 25, 2021

I wrote a simple program that calls a site repeatedly.

I borrowed the example from https://mholt.github.io/curl-to-go/

Then the program crashed when the target site was not available.

The original code:

resp, err := http.Get(url)if err != nil {
// handling
time.Sleep(600)
}
defer resp.Body.Close()

When res is null, defer doesn’t work.

The better code:

resp, err := http.Get(url)if resp != nil {
defer res.Body.Close()
}
if err != nil {
// handling
continue;
}

--

--