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 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) }
}

Info

Never start a real network listener in unit tests – use the httptest package instead.

Previous: Working with Databases – `database/sql` and DriversNext: Logging with `log` and Structured Logging (`zap`)