我正在尝试向路由添加一个简单的用户 ID 验证中间件,如下所示:
api
包装内含:
func RegisterUserRoutes(router *mux.Router) {
router.HandleFunc("/{id}/follower/{follower_id}", user.AddFollower).Methods("POST")
router.HandleFunc("/{id}", user.EditUser).Methods("PUT")
router.HandleFunc("/{id}", user.GetUserByID).Methods("GET")
router.HandleFunc("/", user.GetUser).Methods("GET")
router.HandleFunc("/{id}/blog", user.GetBlogs).Methods("GET")
router.HandleFunc("/{id}/blog_feed", user.GetBlogFeed).Methods("GET")
//Trying to add middleware here
router.HandleFunc("/{id}", user.DeleteUserByID).Methods("DELETE").Subrouter().Use(middleware.ValidateUserID)
router.HandleFunc("/{id}/follower/{follower_id}", user.RemoveFollower).Methods("DELETE")
}
main.go
userRouter := r.PathPrefix("/user").Subrouter()
//A global middleware that validates the JWT included with the request
userRouter.Use(middleware.AuthMiddleware)
api.RegisterUserRoutes(userRouter)
当我在 Postman 中测试端点时,收到 404 未找到错误。似乎将
Use()
与 HandleFunc()
链接起来会使 Gorilla/mux 无法完全匹配路线。如何使用特定的http方法将中间件添加到特定的路由?
//Trying to add middleware here
router.HandleFunc("/{id}", user.DeleteUserByID).Methods("DELETE").Subrouter().Use(middleware.ValidateUserID)
您正在创建一个
Subrouter()
,但没有添加任何 Routes
,因此,对 Subrouter
的任何请求都将导致 Not Found
,因为在 Subrouter
中找不到任何内容。你可以做如下的事情(playground - 简化一点):
func RegisterUserRoutes(router *mux.Router) {
r := router.Path("/{id}").Subrouter()
r.Use(middlewareTwo)
r.HandleFunc("", func(w http.ResponseWriter, _ *http.Request) { w.Write([]byte("test function 2\n")) })
}
以下内容也可以工作,但最初的
Handlefunc
不会被调用,所以它有点毫无意义(playground):
func RegisterUserRoutes(router *mux.Router) {
r := router.
HandleFunc("/{id}", func(w http.ResponseWriter, _ *http.Request) { w.Write([]byte("first HandleFunc\n")) }).
Methods("GET").
Subrouter()
r.Use(middlewareTwo)
r.HandleFunc("", func(w http.ResponseWriter, _ *http.Request) { w.Write([]byte("not found handler2\n")) })
}