如何将中间件应用于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
开头的路径。
答案 0 :(得分: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)
})
}
答案 1 :(得分:1)
使用这些代码,应该可以正常工作?
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")
}
答案 2 :(得分:0)
您可以使用此:
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)
}