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
  • Teach on BraveProgrammer

© 2026 BraveProgrammer. All rights reserved.

Testing HTTP Handlers – Tab | Go Programming Bootcamp lesson | BraveProgrammer
  1. Courses
  2. /
  3. Go Programming Bootcamp

Lesson 57 of 60

·Go

Testing 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) }
        })
    }
}
string
string
int
string
"GET hello"
"/hello"
""
"Hello, World! "
"POST echo"
"/echo"
"ping"
"ping"
// Setup router (could be chi, mux, etc.)
"/hello"
"/echo"
for
range
func(t *testing.T)
if
"status %d, want %d"
if
string
"body %q, want %q"

Info

Table‑driven tests keep your suite DRY and easy to extend.
Make it stickPractice what you've learned1 quiz · 3 practical tests · Optional activities from Go Programming BootcampBrowse activities
Previous lessonGenerating Go Code – `go generate` & TemplatesContinue to lesson 58Building an Observability Dashboard with Prometheus & GrafanaBack to Go Programming Bootcamp curriculum