Skip to main content
Brave Programmer Logo

BraveProgrammer

BraveProgrammer

HomeProjectsBlogsCoursesLessonsAbout

Site footer

BraveProgrammer

Free coding courses, practical tutorials, and real projects from BraveProgrammer. Learn web development with React, Next.js, and TypeScript.

Navigation

  • Home
  • Projects
  • Blogs
  • Courses

Resources

  • About
  • Lessons

© 2026 BraveProgrammer. All rights reserved.

  1. Courses
  2. /
  3. Go Programming Bootcamp

Lesson 57 of 60 · Go

Testing HTTP Handlers – Table‑Driven Approach

Duration: 15 minutes

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       string
        body       string
        wantStatus int
        wantBody   string
    }{
        {"GET hello", http.MethodGet, "/hello", "", http.StatusOK, "Hello, World!\n"},
        {"POST echo", http.MethodPost, "/echo", "ping", http.StatusOK, "ping"},
    }

    // Setup router (could be chi, mux, etc.)
    r := http.NewServeMux()
    r.HandleFunc("/hello", helloHandler)
    r.HandleFunc("/echo", echoHandler)

    for _, tc := range tests {
        t.Run(tc.name, func(t *testing.T) {
            req := httptest.NewRequest(tc.method, tc.path, strings.NewReader(tc.body))
            w := httptest.NewRecorder()
            r.ServeHTTP(w, req)
            resp := w.Result()
            if resp.StatusCode != tc.wantStatus { t.Fatalf("status %d, want %d", resp.StatusCode, tc.wantStatus) }
            b, _ := io.ReadAll(resp.Body)
            if string(b) != tc.wantBody { t.Fatalf("body %q, want %q", b, tc.wantBody) }
        })
    }
}

Info

Table‑driven tests keep your suite DRY and easy to extend.

Previous: Generating Go Code – `go generate` & TemplatesNext: Building an Observability Dashboard with Prometheus & Grafana