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
- A
http.ClientwithTimeoutavoids hanging. defer resp.Body.Close()always releases it.json.NewDecoderdecodes straight from the stream.
Keywords and builtins used here
anydefererrorfuncifreturnstring
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.
Step 4 of 5 in HTTP, step 19 of 26 in Standard library & project layout.