Composable HTTP Middleware Chain

Compose HTTP handlers through middleware that wrap the next handler, adding logging, recovery, and request identifiers without duplication.

GoResilience

Code

gosnippet
35 lines
package main

import (
	"log"
	"net/http"
	"time"
)

type Middleware func(http.Handler) http.Handler

func chain(h http.Handler, middleware ...Middleware) http.Handler {
	for i := len(middleware) - 1; i >= 0; i-- {
		h = middleware[i](h)
	}
	return h
}

func logging(next http.Handler) http.Handler {
	return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		start := time.Now()
		next.ServeHTTP(w, r)
		log.Printf("method=%s path=%s duration=%s", r.Method, r.URL.Path, time.Since(start))
	})
}

func recoverPanic(next http.Handler) http.Handler {
	return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		defer func() {
			if rec := recover(); rec != nil {
				http.Error(w, "internal error", http.StatusInternalServerError)
			}
		}()
		next.ServeHTTP(w, r)
	})
}

How the snippet works

Composable HTTP Middleware Chain is built around the functions chain, logging and recoverPanic.

Repetition is confined to for i := len(middleware) - 1; i >= 0; i-- — the rest of the file is straight-line. A defer statement pins the cleanup to the function boundary rather than scattering it through the body.

Using it

Signature: func chain(h http.Handler, middleware ...Middleware) http.Handler

Key statements

return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
start := time.Now()
next.ServeHTTP(w, r)
log.Printf("method=%s path=%s duration=%s", r.Method, r.URL.Path, time.Since(start))
})
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
defer func() {
if rec := recover(); rec != nil {
http.Error(w, "internal error", http.StatusInternalServerError)
}
}()
next.ServeHTTP(w, r)
})
func chain(h http.Handler, middleware ...Middleware) http.Handler {
for i := len(middleware) - 1; i >= 0; i-- {
h = middleware[i](h)
}
return h
}

Interactive Tools for This Topic

FAQ

Any setup needed beyond the language runtime?
None — the language runtime is the only requirement. Every import resolves inside the standard library — `log`, `net/http`, `time`. The file defines `chain`, `logging`, `recoverPanic` at load time.