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 | Go Programming Bootcamp lesson | BraveProgrammer
  1. Courses
  2. /
  3. Go Programming Bootcamp

Lesson 25 of 60

·Go

Testing HTTP Handlers

20 minutes

Course progress42%

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)
     resp.StatusCode != http.StatusOK || (body) !=  {
        t.Fatalf(, resp.StatusCode, body)
    }
}
if
string
"Hello, Go HTTP! "
"unexpected response: %d %s"

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.
Make it stickPractice what you've learned1 quiz · 3 practical tests · Optional activities from Go Programming BootcampBrowse activities
Previous lessonWorking with Databases – `database/sql` and DriversContinue to lesson 26Logging with `log` and Structured Logging (`zap`)Back to Go Programming Bootcamp curriculum