HTTP JSON request with a context timeout
Go
package main
import (
"context"
"encoding/json"
"fmt"
"io"
"net/http"
"time"
)
// GetJSON fetches and decodes JSON with a deadline and a response size cap.
func GetJSON(ctx context.Context, client *http.Client, url string, target any) error {
ctx, cancel := context.WithTimeout(ctx, 5*time.Second)
defer cancel()
req, err := http.NewRequestWithContext(ctx, http.MethodGet, url, nil)
if err != nil {
return fmt.Errorf("build request: %w", err)
}
req.Header.Set("Accept", "application/json")
resp, err := client.Do(req)
if err != nil {
return fmt.Errorf("get %s: %w", url, err)
}
defer resp.Body.Close()
if resp.StatusCode != http.StatusOK {
return fmt.Errorf("get %s: status %d", url, resp.StatusCode)
}
return json.NewDecoder(io.LimitReader(resp.Body, 1<<20)).Decode(target)
}
func main() {
var payload map[string]any
_ = GetJSON(context.Background(), http.DefaultClient, "https://httpbin.org/json", &payload)
}