Test HTTP handlers and local servers
Test HTTP handlers and local servers
Choose a test boundary according to the behavior you want to verify. httptest.NewRequest and NewRecorder call a handler in memory, making status, headers and body easy to assert. httptest.NewServer exercises the actual client-server exchange over loopback. Neither proves production behavior behind real proxies or under load.
package main
import ( "fmt" "net/http" "net/http/httptest" "strings")
func probe(h http.Handler, method, path, body string) *httptest.ResponseRecorder { w := httptest.NewRecorder() h.ServeHTTP(w, httptest.NewRequest(method, path, strings.NewReader(body))) return w}func health(w http.ResponseWriter, r *http.Request) { w.Header().Set("Content-Type", "text/plain") fmt.Fprint(w, "ready")}func main() { m := http.NewServeMux() m.HandleFunc("GET /health", health) for _, p := range []string{"/health", "/missing"} { w := probe(m, "GET", p, "") fmt.Println(w.Code == 200 && w.Result().Header.Get("Content-Type") == "text/plain" && w.Body.String() == "ready") }}The first predicate describes the health endpoint contract. The second path intentionally does not meet it. Real Go tests use t.Errorf or t.Fatal and should assert the expected 404 separately rather than accepting any failure. A recorder captures writes but does not model connection timeouts or the full protocol.
Expected output:
truefalseCheck HEAD over a real local server
package main
import ( "fmt" "io" "net/http" "net/http/httptest" "time")
func check(e error) { if e != nil { panic(e) }}func health(w http.ResponseWriter, r *http.Request) { w.Header().Set("Content-Type", "text/plain") fmt.Fprint(w, "ready")}func main() { m := http.NewServeMux() m.HandleFunc("GET /health", health) s := httptest.NewServer(m) defer s.Close() c := s.Client() c.Timeout = 2 * time.Second req, e := http.NewRequest("HEAD", s.URL+"/health", nil) check(e) res, e := c.Do(req) check(e) defer res.Body.Close() b, e := io.ReadAll(res.Body) check(e) fmt.Println(res.StatusCode, res.Header.Get("Content-Type"), len(b))}GET matches HEAD under modern ServeMux rules. The real server suppresses the response body for HEAD while retaining appropriate metadata. The test does not depend on dynamic ports. Prefer table-driven tests for valid and invalid inputs; use the accompanying edge_test.go fixture for executable assertions with go test -race.
Expected output:
200 text/plain 0Try it locally
Test POST /health and an unknown GET path using a mux. Print the two expected status codes (405 and 404).
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
HTTP servers 09: Test HTTP handlers and local servers
Check the lesson objective before moving on.
Which fixture exercises actual HTTP transport?
Why test both missing routes and wrong methods?