Middleware is a way to wrap a handler with additional functionality. It is a common pattern in web applications that allows us to write DRY code.
For example, we can write a middleware that logs every request to the server. We can then wrap our handler with this middleware and every request will be logged without us having to write the logging code in every handler.
To do that, we can write the middleware function like this:
func middlewareLog(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)
})
}
Then, any handler that needs logging can be wrapped by this middleware function:
mux.Handle("/app/", middlewareLog(handler))