一尘不染

将中间件与Golang Gorilla Mux子路由器一起使用

go

如何将中间件应用于Go Gorilla Toolkit多路复用器子路由器?

我有以下代码:

router := mux.NewRouter().StrictSlash(true)
apiRouter := router.PathPrefix("/api/").Subrouter()

apiRouter.Methods(http.MethodGet).
    Path("/api/path/to/handler").Handler(handleAPICall)

我想应用一个检查安全性令牌的中间件处理程序,但仅在以开头的那些路径上/api


阅读 321

收藏
2020-07-02

共1个答案

一尘不染

以下似乎有效:

apiRouter := mux.NewRouter()

router.PathPrefix("/api/").Handler(http.StripPrefix("/api",
    adapt(apiRouter, checkTokenHandler)))

apiRouter.Methods(http.MethodGet).
    Path("/path/to/handler").Handler(handleAPICall)
// Note that `/api` has been removed from the path.

哪里

func adapt(h http.Handler, adapters ...func(http.Handler) http.Handler)
    http.Handler {
    for _, adapter := range adapters {
        h = adapter(h)
    }
    return h
}

func checkTokenHandler(h http.Handler) http.Handler {
    return http.HandlerFunc(func(res http.ResponseWriter, req *http.Request) {
        // Check the security cookie.
        h.ServeHTTP(res, req)
    })
}
2020-07-02