

0 / 2 embers
0 / 3000 xp
click for more info
Complete a lesson to start your streak
click for more info
Still calibrating
click for more info
Not enough gems
Cost: 6 gems
1: Middleware
incomplete
2: Stateful Handlers
incomplete
3: Routing
incomplete
4: Patterns
incomplete
This lesson's interactive features are locked, please to keep using them
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))