Gorilla mux custom middleware

前提是你 提交于 2019-11-28 17:03:32

Just create a wrapper, it's rather easy in Go:

func HomeHandler(response http.ResponseWriter, request *http.Request) {

    fmt.Fprintf(response, "Hello home")
}

func Middleware(h http.Handler) http.Handler {
    return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
        log.Println("middleware", r.URL)
        h.ServeHTTP(w, r)
    })
}
func main() {
    r := mux.NewRouter()
    r.HandleFunc("/", HomeHandler)
    http.Handle("/", Middleware(r))
}

I'm not sure why @OneOfOne chose to chain router into the Middleware, I think this is slight better approach:

func main() {
    r.Handle("/",Middleware(http.HandlerFunc(homeHandler)))
    http.Handle("/", r)
}

func Middleware(h http.Handler) http.Handler {
    return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
    h.ServeHTTP(w, r)
})}

If you want to apply a middleware chain to all routes of a router or subrouter you can use a fork of Gorilla mux https://github.com/bezrukovspb/mux

subRouter := router.PathPrefix("/use-a-b").Subrouter().Use(middlewareA, middlewareB)
subRouter.Path("/hello").HandlerFunc(requestHandlerFunc)

You might consider a middleware package such as negroni.

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!