Go HTTP Middleware Chain: Nesting Correctly
In this tutorial, you'll learn about Go HTTP Middleware Chain: Nesting Correctly. We cover key concepts, practical examples, and best practices.
Middleware chains in Go -- Learn the correct way to compose HTTP middleware so logging, auth, and handler logic execute in the expected order.
The Problem
When chaining middleware in Go, the outermost middleware wraps the inner handler. The first middleware applied runs first on the request path but last on the response path. Confusing this order causes logging after responses or auth checks happening too late.
Wrong
http.Handle("/", loggingMiddleware(
authMiddleware(
http.HandlerFunc(finalHandler))))
Output:
$ curl http://localhost:8080/protected
// Response closed before logging sees it -- broken!
Right
func chain(h http.Handler, m ...func(http.Handler) http.Handler) http.Handler {
for i := len(m) - 1; i >= 0; i-- { h = m[i](h) }
return h
}
http.Handle("/", chain(finalHandler, loggingMiddleware, authMiddleware))
Output:
$ curl http://localhost:8080/protected
// logging: REQUEST / auth: OK / handler: done / logging: RESPONSE (200, 42ms)
Prevention
- Apply middleware in the order you want execution
- Use a chain helper function to reverse middleware order
- Use libraries like justinas/alice for readable chains
- Panic recovery must be the outermost wrapper
- Always call next.ServeHTTP(w, r) or the chain breaks
Common Mistakes with http middleware chain
- Using
foldlinstead offoldl'causing stack overflow on large lists - Forgetting
deriving (Show, Eq)on custom data types needed for debugging - Placing the wildcard pattern first in case expressions, making all subsequent patterns unreachable
These mistakes appear frequently in real-world GO code. DodaTech's contributors have identified these patterns through analysis of open-source projects and production systems.
Practice Exercise
Write a pure function that safely divides two integers using Maybe, then test it with edge cases like division by zero and negative numbers.
This exercise reinforces the concepts covered in this guide. Try implementing it before checking online solutions.
FAQ
Built by the developers of Doda Browser, DodaZIP, and Durga Antivirus Pro. DodaTech tutorials help Go developers build production-ready software used by millions.
Built by the developers of DodaTech
Doda Browser, DodaZIP & Durga Antivirus Pro