ProgramGuru

Testing HTTP Handlers

Start with Testing HTTP Handlers

In this lesson, explore testing http handlers through one small Go program, and connect its output to the language rules behind it.

What you’ll learn

  • Explain the main purpose of testing http handlers.
  • Read and run the complete Go example in this lesson.
  • Apply the concept and recognize common mistakes.

Understand the idea

net/http/httptest provides an in-memory response recorder and request constructor. Tests can assert status, headers and bodies without opening a real port.

Test successful and invalid cases; for integration behavior, use an httptest.Server when network-level behavior matters.

Visualize how it works

Follow this diagram before executing the example. Check where a value or decision changes what runs next.

Visual explanation for http testsFast handler tests protect API behavior.Construct requestStep 1Run handlerStep 2Record responseStep 3Assert status/bodyStep 4Fast handler tests protect API behavior.
Fast handler tests protect API behavior.

Tools, syntax and practical notes

handler_test.go

package main
import (
    "net/http"
    "net/http/httptest"
    "testing"
)
func TestHello(t *testing.T) {
    rec := httptest.NewRecorder()
    http.HandlerFunc(hello).ServeHTTP(rec, httptest.NewRequest("GET", "/", nil))
    if rec.Code != 200 || rec.Body.String() != "hello" { t.Fatalf("unexpected response: %d %q", rec.Code, rec.Body.String()) }
}

Run a complete Go example

This example is a complete program. Save it as main.go or paste it into the Go Playground.

Go code

package main

import (
	"fmt"
	"net/http"
	"net/http/httptest"
)

func hello(w http.ResponseWriter, r *http.Request) { fmt.Fprint(w, "hello") }
func main() {
	rec := httptest.NewRecorder()
	http.HandlerFunc(hello).ServeHTTP(rec, httptest.NewRequest("GET", "/", nil))
	fmt.Println("Pass:", rec.Code == 200 && rec.Body.String() == "hello")
}

Output

Pass: true

Trace what the program does

The recorder captures status and body, and the sample prints Pass: true. Put the same expectations in a TestHello function for a real go test run.

Avoid common mistakes

  • Handler tests do not exercise TLS, proxies, and deployment configuration.
  • Check content types as well as bodies for JSON endpoints.

Try it yourself

Add tests for both a successful GET and a rejected method.

Tip: Edit the example above, predict the output, and run the modified code to test your reasoning.

Check your understanding

What does httptest.NewRecorder capture?
Choose one answer. You can try again.

Answer and explanation

An HTTP handler’s response

Correct. The recorder captures status and body, and the sample prints Pass: true.

What you should remember

You have practiced Testing HTTP Handlers in a small, self-contained program. The important habit is to predict what runs, inspect the actual output and distinguish the language rule from the particular example.

Before continuing, make sure you can explain the program to someone who has not seen it, including the line that changes its result.

Reaching the recap and completing the quizzes are separate milestones.

    Next lesson: Introduction to Database Programming →