Test a Go net/http Handler Without Starting a Server
Use net/http/httptest to send JSON requests, check status codes, and test validation paths in memory. After this, you can test HTTP handlers in milliseconds without opening a port.
Skip ahead: If you already separate newRouter() from main(), skip to "Case 3: Go 1.22+ path parameters require router.ServeHTTP" or the comparison table below.
You do not need to bind a TCP port, sleep for startup, or pick a free port just to test an HTTP handler in Go. With net/http/httptest, your tests build an in-memory request, pass it straight to your router, and inspect the recorded status code, headers, and body in milliseconds. Verified on golang:trixie (Go 1.27.4).
Case 1: table-driven POST tests with NewRecorder
Keep route wiring in a helper like newRouter() so main() and your tests exercise the exact same routes, method matching, and validation:
// handler.go
package main
import (
"encoding/json"
"net/http"
)
type orderInput struct {
SKU string `json:"sku"`
Qty int `json:"qty"`
}
func newRouter() http.Handler {
mux := http.NewServeMux()
mux.HandleFunc("POST /orders", func(w http.ResponseWriter, r *http.Request) {
var in orderInput
if err := json.NewDecoder(r.Body).Decode(&in); err != nil || in.SKU == "" || in.Qty < 1 {
http.Error(w, `{"error":"invalid order"}`, http.StatusBadRequest)
return
}
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(http.StatusCreated)
json.NewEncoder(w).Encode(in)
})
return mux
}
httptest.NewRequest builds a server-side *http.Request, and httptest.NewRecorder captures everything your handler writes:
// handler_test.go
package main
import (
"net/http"
"net/http/httptest"
"strings"
"testing"
)
func TestCreateOrder(t *testing.T) {
cases := []struct {
name string
body string
wantCode int
}{
{name: "valid order", body: `{"sku":"A-1","qty":2}`, wantCode: http.StatusCreated},
{name: "zero quantity", body: `{"sku":"A-1","qty":0}`, wantCode: http.StatusBadRequest},
{name: "broken json", body: `{`, wantCode: http.StatusBadRequest},
}
router := newRouter()
for _, tc := range cases {
t.Run(tc.name, func(t *testing.T) {
req := httptest.NewRequest(http.MethodPost, "/orders", strings.NewReader(tc.body))
req.Header.Set("Content-Type", "application/json")
rec := httptest.NewRecorder()
router.ServeHTTP(rec, req)
if rec.Code != tc.wantCode {
t.Fatalf("status = %d, want %d (body=%s)", rec.Code, tc.wantCode, rec.Body.String())
}
})
}
}
go test -v ./...
=== RUN TestCreateOrder
=== RUN TestCreateOrder/valid_order
=== RUN TestCreateOrder/zero_quantity
=== RUN TestCreateOrder/broken_json
--- PASS: TestCreateOrder (0.00s)
--- PASS: TestCreateOrder/valid_order (0.00s)
--- PASS: TestCreateOrder/zero_quantity (0.00s)
--- PASS: TestCreateOrder/broken_json (0.00s)
PASS
ok example.com/orders 0.002s
Case 2: test query parameters, headers, and decoded JSON
Checking only rec.Code misses wrong Content-Type headers or malformed JSON responses. Decode rec.Body into a typed slice or struct instead of comparing fragile whitespace in raw strings:
// handler.go (GET route)
mux.HandleFunc("GET /orders", func(w http.ResponseWriter, r *http.Request) {
status := r.URL.Query().Get("status")
if status == "" {
status = "all"
}
w.Header().Set("Content-Type", "application/json")
json.NewEncoder(w).Encode([]order{{SKU: "A-1", Status: status}})
})
// handler_test.go
func TestListOrders(t *testing.T) {
req := httptest.NewRequest(http.MethodGet, "/orders?status=open", nil)
rec := httptest.NewRecorder()
newRouter().ServeHTTP(rec, req)
if ct := rec.Header().Get("Content-Type"); ct != "application/json" {
t.Fatalf("Content-Type = %q, want application/json", ct)
}
var got []order
if err := json.NewDecoder(rec.Body).Decode(&got); err != nil {
t.Fatalf("decode failed: %v", err)
}
if len(got) != 1 || got[0].Status != "open" {
t.Fatalf("unexpected orders: %+v", got)
}
}
=== RUN TestListOrders
--- PASS: TestListOrders (0.00s)
PASS
ok example.com/orders2 0.002s
Case 3: Go 1.22+ path parameters require router.ServeHTTP
If a route uses Go 1.22+ path parameters like "GET /orders/{id}", calling the handler function directly skips ServeMux pattern matching, so r.PathValue("id") returns "". Always invoke newRouter().ServeHTTP(rec, req):
// handler.go
package main
import (
"fmt"
"net/http"
)
func getOrderByID(w http.ResponseWriter, r *http.Request) {
id := r.PathValue("id")
if id == "" {
http.Error(w, "missing id", http.StatusBadRequest)
return
}
fmt.Fprintf(w, "order:%s", id)
}
func newRouter() http.Handler {
mux := http.NewServeMux()
mux.HandleFunc("GET /orders/{id}", getOrderByID)
return mux
}
// handler_test.go
package main
import (
"net/http"
"net/http/httptest"
"testing"
)
func TestGetOrderByID(t *testing.T) {
// Direct handler call misses PathValue("id")
directRec := httptest.NewRecorder()
getOrderByID(directRec, httptest.NewRequest(http.MethodGet, "/orders/42", nil))
if directRec.Code != http.StatusBadRequest {
t.Fatalf("expected 400 when bypassing mux, got %d", directRec.Code)
}
// Router call populates PathValue("id")
muxRec := httptest.NewRecorder()
newRouter().ServeHTTP(muxRec, httptest.NewRequest(http.MethodGet, "/orders/42", nil))
if muxRec.Code != http.StatusOK || muxRec.Body.String() != "order:42" {
t.Fatalf("unexpected mux response: %d %q", muxRec.Code, muxRec.Body.String())
}
}
=== RUN TestGetOrderByID
--- PASS: TestGetOrderByID (0.00s)
PASS
ok example.com/orders3 0.001s
Case 4: when to use httptest.NewServer instead
httptest.NewRecorder() tests your server handlers in memory without opening a socket. When you are testing an outbound http.Client (checking request headers, retry backoff on 503, or client timeouts), spin up a real local test listener with httptest.NewServer(h) and pass srv.URL to your client.
NewRecorder vs. NewServer
| Helper | Opens a TCP port? | When to use |
|---|---|---|
httptest.NewRecorder() | No (runs in memory) | Testing your own handlers, middleware, and ServeMux routes |
httptest.NewServer(h) | Yes (binds 127.0.0.1:0) | Testing an outbound http.Client (timeouts, retries, TLS) |
Common mistakes
- Calling the handler function directly instead of
router.ServeHTTP: skips method checks (POSTvsGET), middleware, andr.PathValueextraction. - Using
http.NewRequestinstead ofhttptest.NewRequest:http.NewRequestleavesRemoteAddrunset and returns an error you have to check;httptest.NewRequestsets sensible test defaults. - Comparing raw JSON strings with whitespace:
json.NewEncoder(w).Encode(...)appends a trailing newline; decode into a struct instead of asserting exact string equality.
⚠ Warning: Whenever you use httptest.NewServer, always pair it with defer srv.Close()—an unclosed test server leaks sockets and can hang go test.
What happens if you skip this
Tests either bind hardcoded ports like :8080 (failing randomly in CI whenever two test runs overlap) or skip ServeMux and miss broken route patterns and middleware headers until a real client hits the endpoint.
Related course: Go for Beginners.
About
Use net/http/httptest to send JSON requests, check status codes, and test validation paths in memory. After this, you can test HTTP handlers in milliseconds without opening a port.
- Responsible
- Jay P
- Last Update
- 11/27/2026
- Reading Time
- 5 min
Reviews
Sign in to write a reviewComments
Sign in to commentNo comments yet.