Gorilla mux custom middleware

前端 未结 5 1561
醉梦人生
醉梦人生 2020-12-13 01:01

I am using gorilla mux for manage routing. What I am missing is to integrate a middleware between every request.

For example

package main

import (
         


        
相关标签:
5条回答
  • 2020-12-13 01:06

    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)
    
    0 讨论(0)
  • 2020-12-13 01:10

    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))
    }
    
    0 讨论(0)
  • 2020-12-13 01:24
    func Middleware(h http.Handler) http.Handler {
        return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
            // do stuff
            h.ServeHTTP(w, r)
        })
    }
    func Middleware2(s string) mux.MiddlewareFunc {
        return func(h http.Handler) http.Handler {
            return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
                // do stuff
                fmt.Println(s)
                h.ServeHTTP(w, r)
            })
        }
    }
    func main() {
        router := mux.NewRouter()
    
    
        router.Use(Middleware)
        //you can apply it to a sub-router too
        subRouter := router.PathPrefix("/sub_router/").Subrouter()
        subRouter.Use(Middleware2("somePrams"))
        // Add more middleware if you need call router.Use Again
        // router.Use(Middleware3, Middleware4, Middleware5)
    
        _ = http.ListenAndServe(":80", router)
    }
    

    the official doc on the mux website

    0 讨论(0)
  • 2020-12-13 01:29

    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)
    })}
    
    0 讨论(0)
  • 2020-12-13 01:31

    You might consider a middleware package such as negroni.

    0 讨论(0)
提交回复
热议问题