【问题标题】:Using middleware with Golang Gorilla mux subrouters将中间件与 Golang Gorilla mux 子路由器一起使用
【发布时间】:2016-12-21 21:28:26
【问题描述】:

如何将中间件应用到 Go Gorilla Toolkit mux 子路由器?

我有以下代码:

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

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

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

【问题讨论】:

  • 这个link对我有帮助。

标签: go middleware


【解决方案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)
    })
}

【讨论】:

  • 聚会有点晚了,但这实际上并没有使用 Gorilla Mux 的 Subrouter...
【解决方案2】:

使用这些代码,应该可以正常工作?

    r := mux.NewRouter()
    api := r.PathPrefix("/api").Subrouter()
    routes.InitRouteV1(api)

    // handle 404
    r.NotFoundHandler = http.HandlerFunc(func (w http.ResponseWriter, req *http.Request) {
        w.Header().Set("Content-type", "application/json")
        json.NewEncoder(w).Encode(&response.Rsp{Code: http.StatusNotFound,Message: http.StatusText(http.StatusNotFound) })
    })
     // handle method
    r.MethodNotAllowedHandler = http.HandlerFunc(func (w http.ResponseWriter, req *http.Request) {
        w.Header().Set("Content-type", "application/json")
        json.NewEncoder(w).Encode(&response.Rsp{Code: http.StatusMethodNotAllowed,Message: http.StatusText(http.StatusMethodNotAllowed) })
    })
package routes

func InitRouteV1(r *mux.Router){
    r.Use(middleware.ResponseJsonMiddleware)
    r.HandleFunc("/user", controller.User).Methods("GET")
}

【讨论】:

    【解决方案3】:

    你可以用这个:

    router := mux.NewRouter().StrictSlash(true)
    
    apiRoutes := router.PathPrefix("/api").Subrouter()
    apiRoutes.Use(authMiddleware)
    apiRoutes.HandleFunc("/postes", getPostes).Methods("GET")
    apiRoutes.HandleFunc("/postes/new", newPost).Methods("POST")
    

    这是我的 authMidelware:

    func authMiddleware(next http.Handler) http.Handler {
        if len(APP_KEY) == 0 {
            log.Fatal("HTTP server unable to start, expected an APP_KEY for JWT auth")
        }
        jwtMiddleware := jwtmiddleware.New(jwtmiddleware.Options{
            ValidationKeyGetter: func(token *jwt.Token) (interface{}, error) {
                return []byte(APP_KEY), nil
            },
            SigningMethod: jwt.SigningMethodHS256,
        })
        return jwtMiddleware.Handler(next)
    }
    

    【讨论】:

      最近更新 更多