HTTP with Go: Middleware
Implementing HTTP middleware with Golang.
Last updated on: 2024-12-11
In Go, HTTP middleware can be implemented using a closure over a http.Handler. Like so:
type Middleware = func(http.Handler) http.Handler
For example:
func myMiddleware(h http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
log.Println("before handling")
h.ServeHTTP(w, r)
log.Println("after handling")
})
}
To use a middleware, simply wrap it around a `http.Handler`.
wrapped := myMiddleware(handler)
You may want to define a utility function to wrap middleware (ordered from outermost to innermost):
func Wrap(h http.Handler, v ...Middleware) http.Handler {
for i := len(v) - 1; i >= 0; i-- {
h = v[i](h)
}
return h
}
h := Wrap(handler,
trueIPMiddleware,
loggingMiddleware,
)