Lesson 57 of 60
GoTesting HTTP Handlers – Table‑Driven Approach
15 minutes
Course progress95%
Table‑Driven Handler Tests
This lesson explains the main concept clearly with beginner-friendly examples and background so you can learn why the code works.
func TestHandlers(t *testing.T) {
tests := []struct {
name string
method string
path
body
wantStatus
wantBody
}{
{, http.MethodGet, , , http.StatusOK, },
{, http.MethodPost, , , http.StatusOK, },
}
r := http.NewServeMux()
r.HandleFunc(, helloHandler)
r.HandleFunc(, echoHandler)
_, tc := tests {
t.Run(tc.name, {
req := httptest.NewRequest(tc.method, tc.path, strings.NewReader(tc.body))
w := httptest.NewRecorder()
r.ServeHTTP(w, req)
resp := w.Result()
resp.StatusCode != tc.wantStatus { t.Fatalf(, resp.StatusCode, tc.wantStatus) }
b, _ := io.ReadAll(resp.Body)
(b) != tc.wantBody { t.Fatalf(, b, tc.wantBody) }
})
}
}