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
- Making HTTP Requests
- Setting Timeouts and Headers
- Decoding JSON Responses
- Error Handling and Retry Logic