Separate HTTP status from transport errors
Separate HTTP status from transport errors
An HTTP response such as 404 or 503 is not by itself a Client.Do error. Check the Go error first, then the status, then the body against the application contract. A successful status does not guarantee valid JSON or correct business data.
package main
import ( "fmt" "net/http" "net/http/httptest" "time")
func check(err error) { if err != nil { panic(err) }}func fixture(h http.HandlerFunc) (*httptest.Server, *http.Client) { s := httptest.NewServer(h) c := s.Client() c.Timeout = 2 * time.Second return s, c}func main() { s, c := fixture(func(w http.ResponseWriter, r *http.Request) { w.WriteHeader(404) }) defer s.Close() res, e := c.Get(s.URL) check(e) defer res.Body.Close() fmt.Println(e == nil, res.StatusCode)}404 is an HTTP response, not a network outage. Select expected statuses per endpoint: creation may require 201 specifically, not any 2xx.
Expected output:
true 404Convert an unexpected status into an error
package main
import ( "fmt" "net/http" "net/http/httptest" "time")
func check(err error) { if err != nil { panic(err) }}func fixture(h http.HandlerFunc) (*httptest.Server, *http.Client) { s := httptest.NewServer(h) c := s.Client() c.Timeout = 2 * time.Second return s, c}func fetch(c *http.Client, u string) error { res, e := c.Get(u) if e != nil { return e } defer res.Body.Close() if res.StatusCode != 200 { return fmt.Errorf("unexpected status: %d", res.StatusCode) } return nil}func main() { s, c := fixture(func(w http.ResponseWriter, r *http.Request) { w.WriteHeader(503) }) defer s.Close() fmt.Println(fetch(c, s.URL))}This helper checks status only; a real API client must also validate the body. Do not log arbitrary response bodies. When Do returns both a response and error because CheckRedirect rejected a redirect, the response body is already closed. A temporary status does not make every operation safe to retry.
Expected output:
unexpected status: 503Try it locally
Request a local endpoint returning 429. Print status and whether it is 2xx.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
HTTP clients 05: Separate HTTP status from transport errors
Check the lesson objective before moving on.
A server returns 503. What must the caller inspect?
Why avoid logging arbitrary error bodies?