Compose HTTP middleware around handlers
Compose HTTP middleware around handlers
Middleware wraps an http.Handler with another handler. It can perform work before or after calling next.ServeHTTP, or stop the chain by responding early. Composition separates cross-cutting concerns from endpoint logic. A wrapper is shared across requests: mutable state captured by it must be synchronized.
package main
import ( "fmt" "net/http" "net/http/httptest" "strings")
func probe(h http.Handler, method, path, body string) *httptest.ResponseRecorder { w := httptest.NewRecorder() h.ServeHTTP(w, httptest.NewRequest(method, path, strings.NewReader(body))) return w}func wrap(label string, next http.Handler) http.Handler { return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { fmt.Println("before", label) defer fmt.Println("after", label) next.ServeHTTP(w, r) })}func main() { h := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { fmt.Println("handler"); fmt.Fprint(w, "ok") }) w := probe(wrap("A", wrap("B", h)), "GET", "/", "") fmt.Println(w.Body.String())}The outer wrapper enters first and exits last. defer runs during unwinding as well. Choose ordering deliberately: request metadata and logging can wrap inner policy checks so rejected requests are also recorded. Avoid logging sensitive bodies, credentials or arbitrary query strings.
Expected output:
before Abefore Bhandlerafter Bafter AokShort-circuit a request
package main
import ( "fmt" "net/http" "net/http/httptest" "strings")
func probe(h http.Handler, method, path, body string) *httptest.ResponseRecorder { w := httptest.NewRecorder() h.ServeHTTP(w, httptest.NewRequest(method, path, strings.NewReader(body))) return w}func methodOnly(next http.Handler) http.Handler { return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { if r.Method != "GET" { w.Header().Set("Allow", "GET") http.Error(w, "method not allowed", 405) return } next.ServeHTTP(w, r) })}func main() { h := methodOnly(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { fmt.Fprint(w, "ok") })) for _, method := range []string{"GET", "POST"} { w := probe(h, method, "/", "") fmt.Println(w.Code, strings.TrimSpace(w.Body.String())) }}The wrapper deliberately allows only GET in this example. Unlike a ServeMux GET pattern, this custom policy does not allow HEAD. For ordinary routing prefer ServeMux; this demonstrates early return. If wrapping ResponseWriter to measure status, preserve optional capabilities when needed (such as streaming) or provide Unwrap for ResponseController. A method filter is not authorization.
Expected output:
200 ok405 method not allowedTry it locally
Wrap a handler with a header-setting middleware; add X-Lab: yes before calling next. Print header and body.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
HTTP servers 06: Compose HTTP middleware around handlers
Check the lesson objective before moving on.
Which wrapper enters first in A(B(handler))?
What should middleware do after writing a rejection?