← All Exercises

HTTP JSON Client with Timeout

advancedgo~30min

Background

Production HTTP clients need deadlines, status validation, and bounded reads; otherwise a slow or hostile server can stall a goroutine or exhaust memory.

Problem

Implement GetJSON(ctx, client, url, target) error. Attach the context to the request, require status 200, wrap transport errors, return *HTTPError for other statuses, limit the body to 1 MiB, and decode JSON into target.

Input

A context, an *http.Client, a URL, and a pointer to a JSON decode target.

Output

nil after a successful decode, or an error carrying the status code, transport failure, or decode failure.

Sample tests

Sample 1

Input: GET /ok returns {"message":"hello"}
Expected: hello

Sample 2

Input: GET /missing returns 404
Expected: HTTPError status=404

Your solution

Learning objective

Write a defensive JSON HTTP client with context propagation, bounded reads, and typed errors.