httptest
The net/http/httptest package tests HTTP handlers without a listening socket you manage. httptest.NewRecorder captures a response. httptest.NewServer starts a local server for client tests.
Detailed Explanation
A handler is ServeHTTP(w, r). In a test you build httptest.NewRequest(method, path, body) and httptest.NewRecorder(), call handler.ServeHTTP(rec, req), then assert rec.Code and rec.Body. No port, no real TCP, no cleanup of a listener. That is the fast path for unit-testing routing, JSON, and status codes.
NewServer. When you need a real http.Client (redirects, cookies, your SDK), srv := httptest.NewServer(handler); defer srv.Close(). srv.URL is the base. The server runs on localhost with an ephemeral port. Use NewTLSServer for HTTPS client tests.
Request context. NewRequest uses context.Background(). For cancel tests, req = req.WithContext(ctx).
The recorder is an http.ResponseWriter. It buffers headers and body. It does not implement every optional interface (Flusher, Hijacker) unless you wrap it. If the handler type-asserts those, NewServer is the more honest test.
What it costs. Recorder tests are microseconds. NewServer is still local and cheap next to a staging environment. Prefer recorder tests for handler logic; use NewServer when the client stack is under test.
Code Examples
package api
import (
"net/http"
"net/http/httptest"
"testing"
)
func TestHealth(t *testing.T) {
req := httptest.NewRequest(http.MethodGet, "/health", nil)
rec := httptest.NewRecorder()
http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.WriteHeader(http.StatusOK)
}).ServeHTTP(rec, req)
if rec.Code != http.StatusOK {
t.Fatalf("code %d", rec.Code)
}
}func TestClient(t *testing.T) {
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.WriteHeader(http.StatusNoContent)
}))
defer srv.Close()
res, err := http.Get(srv.URL)
if err != nil {
t.Fatal(err)
}
res.Body.Close()
if res.StatusCode != http.StatusNoContent {
t.Fatalf("code %d", res.StatusCode)
}
}Common Gotchas
`rec.Body` is a buffer
read it after `ServeHTTP`, not as a stream during the handler.