Lesson 25 of 60 · Go
Testing HTTP Handlers
Duration: 20 minutes
HTTP Handler Tests
This lesson explains the main concept clearly with beginner-friendly examples and background so you can learn why the code works.
net/http/httptest makes it easy to test servers.
func TestHelloHandler(t *testing.T) {
req := httptest.NewRequest(http.MethodGet, "/hello", nil)
w := httptest.NewRecorder()
helloHandler(w, req)
resp := w.Result()
body, _ := io.ReadAll(resp.Body)
if resp.StatusCode != http.StatusOK || string(body) != "Hello, Go HTTP!\n" {
t.Fatalf("unexpected response: %d %s", resp.StatusCode, body)
}
}
Table‑driven endpoint tests
cases := []struct{ method, path string; want int }{{http.MethodGet, "/ping", 200}}
for _, c := range cases {
req := httptest.NewRequest(c.method, c.path, nil)
w := httptest.NewRecorder()
router.ServeHTTP(w, req)
if w.Code != c.want { t.Errorf("%s %s: got %d, want %d", c.method, c.path, w.Code, c.want) }
}