HTTP Middleware Chain Fundamentals
Wrapping http.Handler and chaining with next
HTTP Middleware Chain Fundamentals is a free Go Academy lesson on CoddyKit — lesson 1 of 4. You can read the complete lesson below for free — then practise it hands-on in the browser with a built-in code editor and a 24/7 AI tutor. It is part of the Go Academy learning path, one of 4 lessons in the course, and your progress syncs across the web and the CoddyKit app.
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)
})
}Applying middleware
Wrap handlers before registering them with the mux:
mux := http.NewServeMux()
mux.Handle("/api/", Logger(Auth(apiHandler)))
http.ListenAndServe(":8080", mux)Middleware chain helper
A chain function applies multiple middleware in a readable, left-to-right order:
func Chain(h http.Handler, ms ...func(http.Handler) http.Handler) http.Handler {
for i := len(ms)-1; i >= 0; i-- { h = ms[i](h) }
return h
}
// Usage: Chain(handler, Logger, Auth, RateLimit)Context in middleware
Attach request-scoped values by creating a derived context and wrapping the request:
func RequestID(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
id := uuid.New().String()
ctx := context.WithValue(r.Context(), reqIDKey, id)
w.Header().Set("X-Request-ID", id)
next.ServeHTTP(w, r.WithContext(ctx))
})
}Response writer wrapper
Capture the status code written by a handler by wrapping the ResponseWriter:
type captureWriter struct {
http.ResponseWriter
status int
}
func (cw *captureWriter) WriteHeader(code int) {
cw.status = code
cw.ResponseWriter.WriteHeader(code)
}Panic recovery middleware
Recover from panics to prevent the server from crashing:
func Recovery(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 Server Error", 500)
}
}()
next.ServeHTTP(w, r)
})
}Order matters
Middleware runs in the order it wraps the handler. Recovery should be outermost (wraps everything). Auth before business logic. Logging usually outermost after Recovery.
Compatibility with third-party routers
Because middleware follows the standard func(http.Handler) http.Handler signature, it is compatible with chi, gorilla/mux, and any router that accepts http.Handler.
Global vs route-specific
Apply middleware globally to the entire mux, or wrap individual handlers for route-specific behaviour. chi's subrouters make group-level middleware cleaner.
Testing middleware
Use httptest.NewRecorder and httptest.NewRequest to test middleware in isolation without starting a real server.
w := httptest.NewRecorder()
r := httptest.NewRequest("GET", "/", nil)
Logger(http.HandlerFunc(noop)).ServeHTTP(w, r)Quick Check
What is the standard net/http middleware signature?
Recap: Middleware Chain
Key points:
- func(http.Handler) http.Handler is the standard signature
- Use a Chain helper to avoid deep nesting
- r.WithContext(ctx) to attach values; capture writer to record status
- Recovery outermost; Auth before business logic; Logging after Recovery
Frequently asked questions
Is the “HTTP Middleware Chain Fundamentals” lesson free?
Yes — the full text of “HTTP Middleware Chain Fundamentals” is free to read here on the web, and the Go Academy course includes 4 lessons in total. To practise it interactively (a built-in code editor and a 24/7 AI tutor) and unlock the rest of the Go Academy course, upgrade to CoddyKit PRO.
What will I learn in “HTTP Middleware Chain Fundamentals”?
Wrapping http.Handler and chaining with next You practise Go Academy with hands-on code you run directly in the browser, and a 24/7 AI tutor answers your questions as you work through the lesson.
Do I need any experience to start Go Academy?
No prior experience is required. Go Academy on CoddyKit is structured for beginners through advanced learners; this is — lesson 1 of 4, so you can start here or from the beginning and move at your own pace.
How long does the “HTTP Middleware Chain Fundamentals” lesson take?
Most CoddyKit lessons take about 5–10 minutes. Each one is bite-sized and interactive, so you make steady progress and pick up exactly where you left off across the web and the app.
Can I write and run code in this Go Academy lesson?
Yes. Every Go Academy lesson includes a built-in code editor, so you write and run real code right in your browser and get instant AI feedback — no local setup required.
All lessons in this course
- HTTP Middleware Chain Fundamentals
- Logging and Request ID Middleware
- Auth and Rate Limiting Middleware
- CORS and Panic Recovery Middleware