Here's a basic example with Go's net/http
:
func main() {
r := http.NewServeMux()
r.HandleFunc("/some-route", SomeHandler)
// Wrap your *ServeMux with a function that looks like
// func SomeMiddleware(h http.Handler) http.Handler
http.ListenAndServe("/", YourMiddleware(r))
}
Middleware might be something like this:
func YourMiddleware(h http.Handler) http.Handler {
fn := func(w http.ResponseWriter, r *http.Request) {
// Do something with the response
w.Header().Set("Server", "Probably Go")
// Call the next handler
h.ServeHTTP(w, r)
}
// Type-convert our function so that it
// satisfies the http.Handler interface
return http.HandlerFunc(fn)
}
If you have a lot of middleware you want to chain, a package like alice can simplify it so you're not Wrapping(AllOf(YourMiddleware(r))))
like that. You could also write your own helper -
func use(h http.Handler, middleware ...func(http.Handler) http.Handler) http.Handler {
for _, m := range middleware {
h = m(h)
}
return h
}
// Example usage:
defaultRouter := use(r, handlers.LoggingHandler, csrf.Protect(key), CORSMiddleware)
http.ListenAndServe(":8000", defaultRouter)