Course › Week 5 · HTTP services with net/http › Day 4 · lesson 32 of 42 · 15 min reading + 60–75 min practice
Middleware
Wrap handlers: logging, an API key check, timeouts and panics recovered.
Laravel middleware is a class with a handle($request, $next) method. In Go it is a function that takes an http.Handler and returns another one, which does something before or after calling the first. Wrapping one handler in another is all there is to it: no kernel, no aliases.
Today: request logging, which needs one new language idea (embedding), an API key check, a safety net for panics, and a timeout, all from the standard library.
The shape
1. http.Handler and http.HandlerFunc
http.Handler is an interface with one method, ServeHTTP(w, r) (the interfaces lesson). The mux is a Handler; so is anything you write with that method. http.HandlerFunc(f) converts a plain function with the handler signature into a Handler: it is a function type with a ServeHTTP method that calls the function.
A middleware takes the next handler and returns http.HandlerFunc(func(w, r) { …; next.ServeHTTP(w, r); … }). Code before the call runs on the way in, code after it on the way out.
2. Struct embedding: a type inside a type
To log the status, the middleware must see what the handler passed to WriteHeader. It hands the handler its own ResponseWriter, which records the status and passes everything on.
statusRecorder embeds http.ResponseWriter: the field has a type and no name. Every method of the embedded value is available on statusRecorder itself, so it satisfies the interface without writing Header and Write by hand. It defines only WriteHeader, which replaces the embedded one and calls it with r.ResponseWriter.WriteHeader. Embedding is Go’s replacement for inheritance: reuse by containing, never by extending.
package main
import (
"fmt"
"log/slog"
"net/http"
"os"
"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"))
}
// 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())
})
}
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.HandleFunc("GET /api/bookings/{id}", showBooking)
handler := logRequests(logger, mux)
_ = apiKey // used from the next section on
logger.Info("listening", "addr", ":8080")
if err := http.ListenAndServe(":8080", handler); err != nil {
logger.Error("server stopped", "err", err)
os.Exit(1)
}
}
HTTP/1.1 200 OK
Content-Length: 3
Content-Type: text/plain; charset=utf-8
okHTTP/1.1 200 OK
Content-Type: application/json
Content-Length: 36
{"data":{"id":5522,"guest":"Omar"}}HTTP/1.1 404 Not Found
Content-Type: text/plain; charset=utf-8
X-Content-Type-Options: nosniff
Content-Length: 19
404 page not foundtime=2026-12-03T19:05:49.185+02:00 level=INFO msg=listening addr=:8080
time=2026-12-03T19:05:49.195+02:00 level=INFO msg=request method=GET path=/api/health status=200 ms=0
time=2026-12-03T19:05:49.204+02:00 level=INFO msg=request method=GET path=/api/bookings/5522 status=200 ms=0
time=2026-12-03T19:05:49.212+02:00 level=INFO msg=request method=GET path=/api/nothing status=404 ms=0The log shows each request after it was answered, with the status and the time it took. The status starts at 200 because a handler that never calls WriteHeader sends 200 when it first writes. _ = apiKey keeps the compiler quiet about the key until the next section uses it.
Middleware you need
3. An API key
The service is called by Laravel, not by browsers, so a shared key is enough: Laravel sends Authorization: Bearer <key> with Http::withToken(). strings.CutPrefix removes Bearer and says whether it was there.
The key is compared with subtle.ConstantTimeCompare, which takes the same time whether the first byte or the last one differs. A plain == returns at the first difference, and an attacker can measure that to guess the key byte by byte.
Only the bookings route is wrapped. mux.Handle registers a Handler (here the wrapped one), where HandleFunc registers a function. The health check stays public, so a load balancer can call it.
package main import ( "crypto/subtle" "fmt" "log/slog" "net/http" "os" "strings" "time") 27 unchanged lines
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"))} // 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) })} 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.HandleFunc("GET /api/bookings/{id}", showBooking) mux.Handle("GET /api/bookings/{id}", requireAPIKey(apiKey, http.HandlerFunc(showBooking))) handler := logRequests(logger, mux) _ = apiKey // used from the next section on logger.Info("listening", "addr", ":8080") if err := http.ListenAndServe(":8080", handler); err != nil { logger.Error("server stopped", "err", err) os.Exit(1) }}
HTTP/1.1 200 OK
Content-Length: 3
Content-Type: text/plain; charset=utf-8
okHTTP/1.1 401 Unauthorized
Content-Type: application/json
Content-Length: 31
{"message":"Unauthenticated."}HTTP/1.1 200 OK
Content-Type: application/json
Content-Length: 36
{"data":{"id":5522,"guest":"Omar"}}time=2026-12-03T19:05:50.148+02:00 level=INFO msg=listening addr=:8080
time=2026-12-03T19:05:50.355+02:00 level=INFO msg=request method=GET path=/api/health status=200 ms=0
time=2026-12-03T19:05:50.363+02:00 level=INFO msg=request method=GET path=/api/bookings/5522 status=401 ms=0
time=2026-12-03T19:05:50.372+02:00 level=INFO msg=request method=GET path=/api/bookings/5522 status=200 ms=0main refuses to start without a key of at least 20 characters, the same rule as Laravel’s APP_KEY: a service that starts with an empty key accepts every request with an empty Bearer.
4. Panics and timeouts
recover() inside a deferred function stops a panic and returns its value (the slices lesson showed what a panic is). net/http already recovers a panic in a handler, but only by logging it and closing the connection: Laravel’s Http client sees a connection error and retries. recoverPanics answers a proper 500 instead, and logs the panic with the path.
http.TimeoutHandler(h, d, body) runs h, and if it has not finished after d, answers 503 with body and cancels the request’s context, so a handler that watches r.Context().Done() stops working, as report does.
18 unchanged lines
package main import ( "crypto/subtle" "fmt" "log/slog" "net/http" "os" "strings" "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.ResponseWriter29 unchanged lines
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))) handler := logRequests(logger, mux) 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 { logger.Error("server stopped", "err", err) os.Exit(1) }}
HTTP/1.1 503 Service Unavailable
Content-Length: 39
Content-Type: text/plain; charset=utf-8
{"message":"The report took too long."}HTTP/1.1 500 Internal Server Error
Content-Type: application/json
Content-Length: 27
{"message":"Server Error"}time=2026-12-03T19:05:51.308+02:00 level=INFO msg=listening addr=:8080
time=2026-12-03T19:05:52.521+02:00 level=INFO msg=request method=GET path=/api/report status=503 ms=1000
time=2026-12-03T19:05:52.530+02:00 level=ERROR msg=panic method=GET path=/api/broken panic="runtime error: index out of range [3] with length 3"
time=2026-12-03T19:05:52.530+02:00 level=INFO msg=request method=GET path=/api/broken status=500 ms=0The report was cut off after one second with a 503; the broken handler’s index out of range (the slices lesson) became a 500 with the panic in the log, and the server kept running. Every request still has its log line, because logRequests is outside recoverPanics.
recover is for this one place: the edge of a request, so one bug cannot take the whole server down. Never use it as try/catch for errors; those are returned.
5. The order
logRequests(logger, recoverPanics(logger, mux)) reads from the outside in: a request passes logRequests, then recoverPanics, then the mux and the route’s own middleware; the response goes back the same way. Put logging first, so even a request that panicked is logged with its final status.
With many middlewares the nesting gets deep, and small helpers like chain(h, m1, m2, m3) are common. The idea stays the same: functions around functions.
Coming from PHP
<?php
namespace App\Http\Middleware;
use Closure;
use Illuminate\Http\Request;
use Symfony\Component\HttpFoundation\Response;
final class RequireApiKey
{
public function handle(Request $request, Closure $next): Response
{
if (! hash_equals((string) config('services.analysis.key'), (string) $request->bearerToken())) {
return response()->json(['message' => 'Unauthenticated.'], 401);
}
return $next($request);
}
}
hash_equals is PHP’s constant-time comparison, $next($request) is next.ServeHTTP(w, r), and the Response it returns is what Go’s statusRecorder reconstructs: in PHP the response is a value you can inspect after $next, in Go it has already been written by then, so you record what passes through.
PracticeA request ID middleware
Exercise: X-Request-Id
Write requestID(next http.Handler) http.Handler: it takes the incoming X-Request-Id header, or makes one with crypto/rand.Text() when there is none, sets it on the response, and logs it in logRequests. Pass it from one middleware to the other with context.WithValue and a private key type, the standard way to carry a request-scoped value. Then send the same ID from Laravel with Http::withHeaders(), and you can follow one request through both logs.
Remember
- Middleware is
func(next http.Handler) http.Handler; logging goes outermost, panic recovery inside it. - Compare secrets with
subtle.ConstantTimeCompare, and refuse to start without one.
Tomorrow: testing handlers with httptest, and shutting the server down without dropping requests.