Gorilla mux custom middleware

2019-01-21 16:58发布

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 (
    "fmt"
    "github.com/gorilla/mux"
    "log"
    "net/http"
    "strconv"
)

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

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

func main() {

    port := 3000
    portstring := strconv.Itoa(port)

    r := mux.NewRouter()
    r.HandleFunc("/", HomeHandler)
    http.Handle("/", r)

    log.Print("Listening on port " + portstring + " ... ")
    err := http.ListenAndServe(":"+portstring, nil)
    if err != nil {
        log.Fatal("ListenAndServe error: ", err)
    }
}

Every incoming request should pass through the middleware. How can I integrate here a midleware?

Update

I will use it in combination with gorilla/sessions, and they say:

Important Note: If you aren't using gorilla/mux, you need to wrap your handlers with context.ClearHandler as or else you will leak memory! An easy way to do this is to wrap the top-level mux when calling http.ListenAndServe:

How can I prevent this scenario?

标签: go gorilla
4条回答
Summer. ? 凉城
2楼-- · 2019-01-21 17:35

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)
})}
查看更多
孤傲高冷的网名
3楼-- · 2019-01-21 17:46

You might consider a middleware package such as negroni.

查看更多
趁早两清
4楼-- · 2019-01-21 17:48

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)
查看更多
SAY GOODBYE
5楼-- · 2019-01-21 17:57

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))
}
查看更多
登录 后发表回答