typestar

An HTTP client in Go

Fetching and decoding JSON with a timeout.

func fetchJSON(url string, out any) error {
    client := &http.Client{Timeout: 10 * time.Second}
    resp, err := client.Get(url)
    if err != nil {
        return err
    }
    defer resp.Body.Close()
    if resp.StatusCode != http.StatusOK {
        return fmt.Errorf("status %d", resp.StatusCode)
    }
    return json.NewDecoder(resp.Body).Decode(out)
}

How it works

  1. A http.Client with Timeout avoids hanging.
  2. defer resp.Body.Close() always releases it.
  3. json.NewDecoder decodes straight from the stream.

Keywords and builtins used here

The run, in numbers

Lines
12
Characters to type
311
Tokens
88
Three-star pace
110 tpm

At the three-star pace of 110 tokens a minute, this run takes about 48 seconds.

Type this snippet

Step 4 of 5 in HTTP, step 19 of 26 in Standard library & project layout.

← Previous Next →