Go’s standard-library httptest package supplies test infrastructure for HTTP clients and handlers. A local test server gives a client a predictable response without relying on a remote service; a response recorder captures a handler’s output for inspection. section 6.5.4 section 8.2.1
For a client test, create a server with httptest.NewServer and an http.HandlerFunc that writes the desired response. Pass the server’s URL to the client and defer Close. Making the client URL configurable removes the hardcoded remote dependency and lets the test exercise the HTTP call locally. section 6.5.4
ts := httptest.NewServer(
http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
fmt.Fprintln(w, "...")
}))
defer ts.Close() #1
A small test server writes a fixed response and is closed when the test finishes. section 6.5.4
To test a handler directly, create a request with http.NewRequest and a recorder with httptest.NewRecorder. Call the handler with both, then check the recorded status, headers, and body. This keeps the test focused on the handler without starting a server. section 8.2.1
Listing 8.12 newgame/handler_test.go: Testing Handle
func TestHandle(t *testing.T) {
req, err := http.NewRequest(
http.MethodPost, "/games", nil) #1
require.NoError(t, err)
recorder := httptest.NewRecorder() #2
Handle(recorder, req) #3
assert.Equal(t, http.StatusCreated, recorder.Code) #4
assert.Equal(t, "application/json",
recorder.Header().Get("Content-Type")) #4
assert.JSONEq(t, `{"id":"",...}`,
recorder.Body.String()) #4
}
The game-creation test checks the status, content type, and JSON response using a recorder and testify assertions. section 8.2.1
Checking HTML output
An index-handler test checks for HTTP 200 and compares the recorded body with a golden file in testdata. Exact string comparison is simple but brittle: tabs, carriage returns, or other harmless output changes can fail the test. section 11.1.1



