Middleware
A middleware is a function executed before and/or after the handler, allowing you to do everyday tasks such as logging, authentication, authorization, and so on. The approach we will follow to build middleware in Go is to wrap our handler function with another function. This approach is known in other languages as the decorator pattern. I think it is going to be easier to understand with an example.
Let’s say that I want to log every request that is made to my API before it is done, and after it is done, I could do something like this:
func logRequest(next http.HandlerFunc) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
log.Printf("Before %s %s %s", r.Method, r.URL.Path, r.RemoteAddr)
next(w, r)
log.Printf("After %s %s %s", r.Method, r.URL.Path, r.RemoteAddr)
}
}
As you can see here, a middleware is a function that receives a handler function and returns a new handler function, which is the...