0PricingLogin
Go Academy · Lesson

Decoding JSON Responses

Parsing API responses into Go structs

Check status before decoding

Always verify the response status is 2xx before attempting to decode the body. Non-2xx responses may contain HTML error pages, not JSON.

if resp.StatusCode < 200 || resp.StatusCode >= 300 {
    body, _ := io.ReadAll(resp.Body)
    return fmt.Errorf("status %d: %s", resp.StatusCode, body)
}

json.NewDecoder

Stream-decode the response body without loading it fully into memory:

var result APIResponse
if err := json.NewDecoder(resp.Body).Decode(&result); err != nil {
    return fmt.Errorf("decode: %w", err)
}

All lessons in this course

  1. Making HTTP Requests
  2. Setting Timeouts and Headers
  3. Decoding JSON Responses
  4. Error Handling and Retry Logic
← Back to Go Academy