英文:
Using middleware with Golang Gorilla mux subrouters
问题
你可以使用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
开头的路径上应用安全令牌检查的中间件处理程序,你可以按照以下步骤进行操作:
- 创建一个中间件处理程序,用于检查安全令牌。例如:
func securityMiddleware(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
// 在这里进行安全令牌检查的逻辑
// 如果安全令牌有效,则继续处理请求
// 否则,可以返回错误响应或重定向到其他页面
next.ServeHTTP(w, r)
})
}
- 在需要应用中间件的路径上使用
apiRouter.Use()
方法来添加中间件处理程序。例如:
apiRouter.Use(securityMiddleware)
这样,只有以/api
开头的路径上的请求才会经过安全令牌检查的中间件处理程序。其他路径上的请求将不受影响。
希望对你有帮助!
英文:
How can I apply middleware to a Go Gorilla Toolkit mux subrouter?
I have the following code:
router := mux.NewRouter().StrictSlash(true)
apiRouter := router.PathPrefix("/api/").Subrouter()
apiRouter.Methods(http.MethodGet).
Path("/api/path/to/handler").Handler(handleAPICall)
I want to apply a middleware handler that checks a security token, but only on those paths that start with /api
.
答案1
得分: 2
以下似乎是有效的代码:
apiRouter := mux.NewRouter()
router.PathPrefix("/api/").Handler(http.StripPrefix("/api",
adapt(apiRouter, checkTokenHandler)))
apiRouter.Methods(http.MethodGet).
Path("/path/to/handler").Handler(handleAPICall)
// 注意路径中已经删除了 `/api`。
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) {
// 检查安全 cookie。
h.ServeHTTP(res, req)
})
}
英文:
The following seems to work:
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.
where
func adapt(h http.Handler, adapters ...func(http.Handler) http.Handler)
http.Handler {
for _, adapter := range adapters {
h = adapter(h)
}
return h
}
and
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)
})
}
答案2
得分: 1
使用以下代码,应该可以正常工作 😄
r := mux.NewRouter()
api := r.PathPrefix("/api").Subrouter()
routes.InitRouteV1(api)
// 处理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) })
})
// 处理方法不允许
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")
}
希望对你有帮助!如果还有其他问题,请随时提问。
英文:
use these code ,should work fine 😄
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
得分: 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")
这是我的authMiddleware:
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)
}
英文:
You can use this:
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")
this is my 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)
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论