Skip to content

Instantly share code, notes, and snippets.

@chmike
Last active November 8, 2019 10:00
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save chmike/fd007863a710075456f1bfbe2cff7cec to your computer and use it in GitHub Desktop.
Save chmike/fd007863a710075456f1bfbe2cff7cec to your computer and use it in GitHub Desktop.
Correct HTTP GET response handling
res, err := http.GET(...)
if res != nil {
defer func() {
_, err = io.Copy(ioutil.Discard, res.Body)
res.Body.Close()
}()
}
if err != nil {
// . . .
}
@chmike
Copy link
Author

chmike commented Nov 8, 2019

Adding a timeout to Get. By default there is no timeout.

client := http.Client{Timeout: time.Minute}
res, err := client.Get("...")
if res != nil {
    defer res.Body.Close()
}
if err != nil {
    log.Fatal(err)
}
b, _ := ioutil.ReadAll(res.Body)
...

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment