Hello good people!
I read this post from Mat Ryer: https://medium.com/@matryer/writing-middleware-in-golang-and-how-go-makes-it-so-much-fun-4375c1246e81#.np52sscso
And he makes use of this adapter:
func Adapt(h http.Handler, adapters ...Adapter) http.Handler {
for _, adapter := range adapters {
h = adapter(h)
}
return h
}
Each handler that is passed to the Adapt
function has an h.ServeHTTP(w, r)
like this one:
func Notify() Adapter {
return func(h http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
log.Println("before")
defer log.Println("after")
h.ServeHTTP(w, r)
}
}
}
For what I understand, in each iteration the h
will be overwritten by the next adapter, am I correct? And why the h.ServeHTTP(w, r)
is not executed in each iteration in case there are multiple handlers like this? Is it chaining? If so, why?
http.Handle("/", Adapt(indexHandler, AddHeader("Server", "Mine"),
CheckAuth(providers),
CopyMgoSession(db),
Notify(logger),
)