Chaining Middleware in Go

Chris Gregory
Nov 12, 2017 · 3 min read

func LogMiddleware(h http.HandlerFunc) http.HandlerFunc {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {

log.SetOutput(os.Stdout) // logs go to Stderr by default
log.Println(r.Method, r.URL)
h.ServeHTTP(w, r) // call ServeHTTP on the original handler

})
}
package mainimport (
"fmt"
"net/http"
)
func IndexHandler(w http.ResponseWriter, r *http.Request) {
fmt.Fprintf(w, "Hello Index!")
}
func main() {
http.HandleFunc("/", LogMiddleware(IndexHandler))
http.ListenAndServe(":8080", nil)
}
http.HandleFunc("/",
RequireAuthMiddleware(
SomeOtherMiddleware(
LogMiddleware(IndexHandler))))

type Middleware func(http.HandlerFunc) http.HandlerFuncfunc MultipleMiddleware(h http.HandlerFunc, m ...Middleware) http.HandlerFunc {

if len(m) < 1 {
return h
}

wrapped := h

// loop in reverse to preserve middleware order
for i := len(m) - 1; i >= 0; i-- {
wrapped = m[i](wrapped)
}

return wrapped

}
http.HandleFunc("/",
RequireAuthMiddleware(
SomeOtherMiddleware(
LogMiddleware(IndexHandler))))
http.HandleFunc("/", MultipleMiddleware(IndexHandler,
RequireAuthMiddleware,
SomeOtherMiddleware,
LogMiddleware))
commonMiddleware := []Middleware{
RequireAuthMiddleware,
SomeOtherMiddleware,
LogMiddleware,
}
http.HandleFunc("/foo", MultipleMiddleware(FooHandler, commonMiddleware...)
http.HandleFunc("/bar", MultipleMiddleware(BarHandler, commonMiddleware...)
http.HandleFunc("/baz", MultipleMiddleware(BazHandler, commonMiddleware...)

endpoints := map[string]http.HandlerFunc{
"/foo": FooHandler,
"/bar": BarHandler,
"/baz": BazHandler,
}
for endpoint, f := range endpoints {
http.HandleFunc(endpoint, MultipleMiddleware(f, commonMiddleware))
}

Welcome to a place where words matter. On Medium, smart voices and original ideas take center stage - with no ads in sight. Watch
Follow all the topics you care about, and we’ll deliver the best stories for you to your homepage and inbox. Explore
Get unlimited access to the best stories on Medium — and support writers while you’re at it. Just $5/month. Upgrade