Go Playbook

Course › Week 5 · HTTP services with net/http › Day 5 · lesson 33 of 42 · 20 min reading + 75 min practice

Tests and graceful shutdown

Test handlers with httptest, and stop the server without dropping requests.

httptestgraceful shutdownsignal.NotifyContext

On this page
  1. Testing handlers
  2. Testing clients
  3. Ready for production
  4. Coming from PHP
  5. Practice
  6. Remember

Laravel’s $this->getJson('/api/bookings/1') runs a request through the app without a server. Go’s net/http/httptest does the same with two pieces: a fake request, and a recorder that collects what the handler wrote. Because a handler is just a function, there is nothing to boot.

Then two things a service needs before production: timeouts on the server itself, and a shutdown that lets requests in flight finish when a deploy stops the process.

Testing handlers

1. The code under test

The routes and the API key middleware of the middleware lesson, with one change: the whole mux comes from a routes(apiKey) function, so main and the tests build exactly the same handler.

service/routes.gonew file
package main

import (
	"crypto/subtle"
	"fmt"
	"net/http"
	"strings"
)

// routes is the whole HTTP surface of the service, so tests and main use the same one.
func routes(apiKey string) http.Handler {
	mux := http.NewServeMux()
	mux.HandleFunc("GET /api/health", func(w http.ResponseWriter, r *http.Request) {
		fmt.Fprintln(w, "ok")
	})
	mux.Handle("GET /api/bookings/{id}", requireAPIKey(apiKey, http.HandlerFunc(showBooking)))
	return mux
}

func showBooking(w http.ResponseWriter, r *http.Request) {
	w.Header().Set("Content-Type", "application/json")
	fmt.Fprintf(w, "{\"data\":{\"id\":%s,\"guest\":\"Omar\"}}\n", r.PathValue("id"))
}

// requireAPIKey answers 401 unless the request carries "Authorization: Bearer <key>".
func requireAPIKey(key string, next http.Handler) http.Handler {
	return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		given, ok := strings.CutPrefix(r.Header.Get("Authorization"), "Bearer ")
		if !ok || subtle.ConstantTimeCompare([]byte(given), []byte(key)) != 1 {
			w.Header().Set("Content-Type", "application/json")
			w.WriteHeader(http.StatusUnauthorized)
			fmt.Fprintln(w, "{\"message\":\"Unauthenticated.\"}")
			return
		}
		next.ServeHTTP(w, r)
	})
}

2. httptest.NewRecorder

httptest.NewRequest(method, path, body) builds a request as the server would receive it. httptest.NewRecorder() is an http.ResponseWriter that keeps everything: rec.Code, rec.Header() and rec.Body. Call the handler’s ServeHTTP with both, then check the recorder.

The test is a table (the tests lesson): each case is a request and what must come back. It runs the real mux, so the 405 is tested too, and the middleware with every kind of key.

service/routes_test.gonew file
package main

import (
	"net/http"
	"net/http/httptest"
	"strings"
	"testing"
)

const testKey = "test-key-0123456789abcdef"

func TestRoutes(t *testing.T) {
	handler := routes(testKey)

	tests := []struct {
		name       string
		method     string
		path       string
		auth       string
		wantStatus int
		wantBody   string
	}{
		{name: "health is public", method: "GET", path: "/api/health", wantStatus: 200, wantBody: "ok"},
		{name: "a booking needs the key", method: "GET", path: "/api/bookings/5522", wantStatus: 401, wantBody: "Unauthenticated."},
		{name: "a wrong key", method: "GET", path: "/api/bookings/5522", auth: "Bearer nope", wantStatus: 401},
		{name: "the right key", method: "GET", path: "/api/bookings/5522", auth: "Bearer " + testKey, wantStatus: 200, wantBody: `"id":5522`},
		{name: "a POST is not allowed", method: "POST", path: "/api/health", wantStatus: 405},
	}

	for _, tt := range tests {
		t.Run(tt.name, func(t *testing.T) {
			req := httptest.NewRequest(tt.method, tt.path, nil)
			if tt.auth != "" {
				req.Header.Set("Authorization", tt.auth)
			}
			rec := httptest.NewRecorder()

			handler.ServeHTTP(rec, req)

			if rec.Code != tt.wantStatus {
				t.Errorf("%s %s = %d, want %d", tt.method, tt.path, rec.Code, tt.wantStatus)
			}
			if !strings.Contains(rec.Body.String(), tt.wantBody) {
				t.Errorf("body = %q, want it to contain %q", rec.Body.String(), tt.wantBody)
			}
			if rec.Code == http.StatusUnauthorized && rec.Header().Get("Content-Type") != "application/json" {
				t.Errorf("a 401 must be JSON, got %q", rec.Header().Get("Content-Type"))
			}
		})
	}
}
$ go test -run TestRoutes -v
=== RUN   TestRoutes
=== RUN   TestRoutes/health_is_public
=== RUN   TestRoutes/a_booking_needs_the_key
=== RUN   TestRoutes/a_wrong_key
=== RUN   TestRoutes/the_right_key
=== RUN   TestRoutes/a_POST_is_not_allowed
--- PASS: TestRoutes (0.00s)
    --- PASS: TestRoutes/health_is_public (0.00s)
    --- PASS: TestRoutes/a_booking_needs_the_key (0.00s)
    --- PASS: TestRoutes/a_wrong_key (0.00s)
    --- PASS: TestRoutes/the_right_key (0.00s)
    --- PASS: TestRoutes/a_POST_is_not_allowed (0.00s)
PASS
ok  	service	0.004s

No port, no network, no server: each case runs in microseconds. It is Laravel’s HTTP test, with the request and response as plain values.

Testing clients

3. httptest.NewServer instead of Http::fake

Code that calls an API is tested against a real server on a random local port: httptest.NewServer(handler) starts one, api.URL is its address, and api.Client() a client for it. The handler plays the API, answering each path the way the real one would, including its failures.

fetchBooking takes the base URL as a parameter for exactly this reason: in production it is the configured API, in the test it is api.URL.

service/client.gonew file
package main

import (
	"context"
	"encoding/json/v2"
	"fmt"
	"net/http"
)

type Booking struct {
	ID    int    `json:"id"`
	Guest string `json:"guest"`
}

// fetchBooking asks the bookings API at baseURL for one booking.
func fetchBooking(ctx context.Context, client *http.Client, baseURL string, id int) (Booking, error) {
	req, err := http.NewRequestWithContext(ctx, http.MethodGet, fmt.Sprintf("%s/api/bookings/%d", baseURL, id), nil)
	if err != nil {
		return Booking{}, err
	}
	resp, err := client.Do(req)
	if err != nil {
		return Booking{}, fmt.Errorf("fetching booking %d: %w", id, err)
	}
	defer resp.Body.Close()
	if resp.StatusCode != http.StatusOK {
		return Booking{}, fmt.Errorf("fetching booking %d: status %d", id, resp.StatusCode)
	}
	var body struct {
		Data Booking `json:"data"`
	}
	if err := json.UnmarshalRead(resp.Body, &body); err != nil {
		return Booking{}, fmt.Errorf("decoding booking %d: %w", id, err)
	}
	return body.Data, nil
}
service/client_test.gonew file
package main

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

func TestFetchBooking(t *testing.T) {
	api := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		switch r.URL.Path {
		case "/api/bookings/5522":
			fmt.Fprintln(w, `{"data": {"id": 5522, "guest": "Omar"}}`)
		case "/api/bookings/500":
			w.WriteHeader(http.StatusInternalServerError)
		default:
			w.WriteHeader(http.StatusNotFound)
		}
	}))
	defer api.Close()

	got, err := fetchBooking(context.Background(), api.Client(), api.URL, 5522)
	if err != nil {
		t.Fatalf("fetchBooking returned an error: %v", err)
	}
	if want := (Booking{ID: 5522, Guest: "Omar"}); got != want {
		t.Errorf("fetchBooking = %+v, want %+v", got, want)
	}

	for _, id := range []int{404, 500} {
		if _, err := fetchBooking(context.Background(), api.Client(), api.URL, id); err == nil {
			t.Errorf("fetchBooking(%d) returned no error", id)
		}
	}
}
$ go test -run TestFetchBooking -v
=== RUN   TestFetchBooking
--- PASS: TestFetchBooking (0.00s)
PASS
ok  	service	0.006s

defer api.Close() stops the server at the end of the test. Laravel’s Http::fake() replaces the client; httptest.NewServer replaces the server, so the real client code runs, timeouts and status checks included.

Ready for production

4. Server timeouts

http.ListenAndServe uses a server with no timeouts at all: a client that opens a connection and sends one byte a minute holds it forever, and a few thousand such clients (a “slowloris” attack) use up the server. An http.Server with timeouts closes them:

FieldLimitsHere
ReadHeaderTimeoutthe time to send the request line and headers5 s: the one every server needs
ReadTimeoutthe time to read the whole request, body included30 s
WriteTimeoutthe time from the end of the headers to the end of the response60 s: longer than any handler’s own timeout
IdleTimeouthow long a keep-alive connection waits for the next request120 s

5. Graceful shutdown

A deploy stops the old process with SIGTERM. Killed at once, it drops every request in flight, and Laravel’s client sees connection errors. srv.Shutdown(ctx) instead stops accepting connections, waits for the requests in flight to finish (or for ctx to end), then returns.

signal.NotifyContext returns a context that ends when one of the signals arrives (the context lesson). The server runs in a goroutine and reports its result on a channel (the channels lesson); main waits for whichever comes first, a failure to serve or a signal.

service/main.gochanged since lesson 32: +41 −88
package main import (	"crypto/subtle"	"fmt"	"context"	"errors"	"log/slog"	"net/http"	"os"	"strings"	"os/signal"	"syscall"	"time") func health(w http.ResponseWriter, r *http.Request) {	fmt.Fprintln(w, "ok")} func showBooking(w http.ResponseWriter, r *http.Request) {	w.Header().Set("Content-Type", "application/json")	fmt.Fprintf(w, "{\"data\":{\"id\":%s,\"guest\":\"Omar\"}}\n", r.PathValue("id"))} func report(w http.ResponseWriter, r *http.Request) {	select {	case <-time.After(3 * time.Second): // a report that takes too long		fmt.Fprintln(w, "report ready")	case <-r.Context().Done():		// The client or a timeout gave up: stop working.	}} func broken(w http.ResponseWriter, r *http.Request) {	parts := strings.Split(r.URL.Path, "/")	fmt.Fprintln(w, "property:", parts[3]) // a bug: /api/broken has only 3 parts} // statusRecorder is an http.ResponseWriter that remembers the status it was given.type statusRecorder struct {	http.ResponseWriter	status int} func (r *statusRecorder) WriteHeader(status int) {	r.status = status	r.ResponseWriter.WriteHeader(status)} // logRequests logs one line per request, after it has been answered.func logRequests(logger *slog.Logger, next http.Handler) http.Handler {	return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {		start := time.Now()		rec := &statusRecorder{ResponseWriter: w, status: http.StatusOK}		next.ServeHTTP(rec, r)		logger.Info("request", "method", r.Method, "path", r.URL.Path, "status", rec.status, "ms", time.Since(start).Milliseconds())	})} // requireAPIKey answers 401 unless the request carries "Authorization: Bearer <key>".func requireAPIKey(key string, next http.Handler) http.Handler {	return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {		given, ok := strings.CutPrefix(r.Header.Get("Authorization"), "Bearer ")		if !ok || subtle.ConstantTimeCompare([]byte(given), []byte(key)) != 1 {			w.Header().Set("Content-Type", "application/json")			w.WriteHeader(http.StatusUnauthorized)			fmt.Fprintln(w, "{\"message\":\"Unauthenticated.\"}")			return		}		next.ServeHTTP(w, r)	})} // recoverPanics turns a panic in a handler into a logged 500, instead of a dropped connection.func recoverPanics(logger *slog.Logger, next http.Handler) http.Handler {	return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {		defer func() {			if v := recover(); v != nil {				logger.Error("panic", "method", r.Method, "path", r.URL.Path, "panic", v)				w.Header().Set("Content-Type", "application/json")				w.WriteHeader(http.StatusInternalServerError)				fmt.Fprintln(w, "{\"message\":\"Server Error\"}")			}		}()		next.ServeHTTP(w, r)	})} func main() {	logger := slog.New(slog.NewTextHandler(os.Stderr, nil))	apiKey := os.Getenv("SERVICE_API_KEY")	if len(apiKey) < 20 {		logger.Error("SERVICE_API_KEY must be set, at least 20 characters")		os.Exit(1)	} 	mux := http.NewServeMux()	mux.HandleFunc("GET /api/health", health)	mux.Handle("GET /api/bookings/{id}", requireAPIKey(apiKey, http.HandlerFunc(showBooking)))	mux.Handle("GET /api/report", requireAPIKey(apiKey, http.TimeoutHandler(http.HandlerFunc(report), time.Second, "{\"message\":\"The report took too long.\"}")))	mux.HandleFunc("GET /api/broken", broken) 	// The outermost runs first: log everything, including what a panic turned into.	handler := logRequests(logger, recoverPanics(logger, mux)) 	logger.Info("listening", "addr", ":8080")	if err := http.ListenAndServe(":8080", handler); err != nil {	srv := &http.Server{		Addr:              ":8080",		Handler:           routes(apiKey),		ReadHeaderTimeout: 5 * time.Second,		ReadTimeout:       30 * time.Second,		WriteTimeout:      60 * time.Second,		IdleTimeout:       120 * time.Second,	} 	// ctx ends on Ctrl-C (SIGINT) or on SIGTERM, the signal Docker, systemd and Forge send to stop.	ctx, stop := signal.NotifyContext(context.Background(), os.Interrupt, syscall.SIGTERM)	defer stop() 	serveErr := make(chan error, 1)	go func() {		logger.Info("listening", "addr", srv.Addr)		serveErr <- srv.ListenAndServe()	}() 	select {	case err := <-serveErr:		logger.Error("server stopped", "err", err)		os.Exit(1)	}	case <-ctx.Done():	} 	// Stop accepting new connections, and give the requests in flight 25 seconds to finish.	logger.Info("shutting down")	shutdownCtx, cancel := context.WithTimeout(context.Background(), 25*time.Second)	defer cancel()	if err := srv.Shutdown(shutdownCtx); err != nil {		logger.Error("shutdown did not finish", "err", err)		os.Exit(1)	}	if err := <-serveErr; !errors.Is(err, http.ErrServerClosed) {		logger.Error("server stopped", "err", err)		os.Exit(1)	}	logger.Info("stopped cleanly")}
$ curl -s -i http://127.0.0.1:8080/api/health
HTTP/1.1 200 OK
Content-Length: 3
Content-Type: text/plain; charset=utf-8

ok
the server’s log (stderr), after Ctrl-C
time=2026-12-03T19:07:18.447+02:00 level=INFO msg=listening addr=:8080
time=2026-12-03T19:07:18.661+02:00 level=INFO msg="shutting down"
time=2026-12-03T19:07:18.661+02:00 level=INFO msg="stopped cleanly"

The page stops the server with Ctrl-C after the request: shutting down, then stopped cleanly, and exit code 0. After Shutdown, ListenAndServe returns http.ErrServerClosed, which means “stopped on purpose”; anything else is a real failure.

The 25 seconds must be shorter than what the platform waits before it kills the process for good: Docker waits 10 seconds by default (stop_grace_period changes it), Kubernetes 30. Set them together.

Coming from PHP

tests/Feature/BookingApiTest.php
<?php
public function test_a_booking_needs_the_key(): void
{
    $this->getJson('/api/bookings/5522')->assertUnauthorized();
}

public function test_fetching_a_booking(): void
{
    Http::fake(['bookings.test/api/bookings/5522' => Http::response(['data' => ['id' => 5522]])]);
    // ...
}

Feature tests and Http::fake map one to one onto httptest.NewRecorder and httptest.NewServer. The Go versions need no framework and no fakes registered globally, so tests can run in parallel with t.Parallel() without stepping on each other.

PHP-FPM handles shutdown for you: it finishes the request and exits the worker. A Go service is the process, so draining in-flight requests is code you write once, in main.

PracticeLearn Go with Tests: Command line & package structure; test the panic path

Do Command line & package structure in Learn Go with Tests: it splits one module into a library and two programs, the layout a service with a CLI grows into.

Exercise: test recoverPanics

Add recoverPanics from the middleware lesson to this service and write a test that wraps a handler which panics, sends it a request with a recorder, and checks for a 500 with a JSON body. Give it a logger that writes to a strings.Builder (the interfaces lesson), and check that the panic’s message is in the log.

Remember

  • Test handlers with httptest.NewRecorder, clients with httptest.NewServer.
  • A production server has timeouts and stops with Shutdown on SIGTERM, inside the platform’s grace period.

Tomorrow is the build day: the analysis service Laravel calls, with batches that survive retries and deploys.