HTTP Middleware Chain Composition

Compose request middleware as http.Handler wrappers so logging, recovery, and auth stack in a readable order.

GoResilience

Code

gosnippet
48 lines
package main

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

type middleware func(http.Handler) http.Handler

func chain(h http.Handler, mws ...middleware) http.Handler {
	// 逆序包裹:第一个 middleware 在最外层
	for i := len(mws) - 1; i >= 0; i-- {
		h = mws[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("%s %s took %s", r.Method, r.URL.Path, time.Since(start))
	})
}

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

func main() {
	handler := chain(
		http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
			w.Write([]byte("ok"))
		}),
		logging,
		recovery,
	)
	log.Println("middleware chain ready:", handler != nil)
}

Behavior at a glance

Count the functions chain, logging, recovery and main as the entire surface area of HTTP Middleware Chain Composition.

Iteration happens inside for i := len(mws) - 1; i >= 0; i-- — everything outside it runs once. The cleanup call is deferred to function exit — success, early return, and panic all covered.

Applying it

Entry signature: func chain(h http.Handler, mws ...middleware) http.Handler

Launch the file; main takes over and steps through chain.

Statements that matter

return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
start := time.Now()
next.ServeHTTP(w, r)
log.Printf("%s %s took %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 {
log.Printf("panic recovered: %v", rec)
http.Error(w, "internal error", http.StatusInternalServerError)
}
}()
next.ServeHTTP(w, r)
})
func chain(h http.Handler, mws ...middleware) http.Handler {
// 逆序包裹:第一个 middleware 在最外层
for i := len(mws) - 1; i >= 0; i-- {
h = mws[i](h)
}
return h
}

Interactive Tools for This Topic

FAQ

How do you run HTTP Middleware Chain Composition?
Execute it straight away — the program needs nothing beyond the runtime.