HTTP Middleware Chain Fundamentals
Wrapping http.Handler and chaining with next
Middleware in net/http
In Go's standard library, middleware is a function that accepts an http.Handler and returns a new http.Handler with additional behaviour wrapped around the original.
type Middleware func(http.Handler) http.HandlerBasic middleware
The inner HandlerFunc wraps the original handler with pre/post logic:
func Logger(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
log.Printf("→ %s %s", r.Method, r.URL.Path)
next.ServeHTTP(w, r)
log.Printf("← %s %s done", r.Method, r.URL.Path)
})
}All lessons in this course
- HTTP Middleware Chain Fundamentals
- Logging and Request ID Middleware
- Auth and Rate Limiting Middleware
- CORS and Panic Recovery Middleware