使用 Gin 访问中间件中的路由
Accessing route in middleware using Gin
我的 Golang API 中有一个 user.save
路由(下方),可用于 create
和 update
用户,具体取决于 [=15] =] 在请求对象中提供。该路由使用其他路由也使用的 auth
中间件。
api.POST("/user.save", auth(), user.Save())
api.POST("/user.somethingElse", auth(), user.SomethingElse())
这是我的中间件:
func auth() gin.HandlerFunc {
return func(c *gin.Context) {
//I would like to know here if user.save was the route called
//do authy stuff
}
}
我在想,如果我可以在 auth
中间件中检测到是否调用了 user.save
路由,那么我可以检查是否包含 id
并决定是否继续或 return.
您可以从身份验证处理程序检查 url。实际请求在上下文中,所以很简单:
if c.Request.URL.Path == "/user.save" {
// Do your thing
}
另一种解决方案是参数化您的身份验证中间件,如下所示:
api.POST("/user.save", auth(true), user.Save())
api.POST("/user.somethingElse", auth(false), user.SomethingElse())
func auth(isUserSave bool) gin.HandlerFunc {
return func(c *gin.Context) {
if isUserSave {
// Do your thing
}
}
}
我的 Golang API 中有一个 user.save
路由(下方),可用于 create
和 update
用户,具体取决于 [=15] =] 在请求对象中提供。该路由使用其他路由也使用的 auth
中间件。
api.POST("/user.save", auth(), user.Save())
api.POST("/user.somethingElse", auth(), user.SomethingElse())
这是我的中间件:
func auth() gin.HandlerFunc {
return func(c *gin.Context) {
//I would like to know here if user.save was the route called
//do authy stuff
}
}
我在想,如果我可以在 auth
中间件中检测到是否调用了 user.save
路由,那么我可以检查是否包含 id
并决定是否继续或 return.
您可以从身份验证处理程序检查 url。实际请求在上下文中,所以很简单:
if c.Request.URL.Path == "/user.save" {
// Do your thing
}
另一种解决方案是参数化您的身份验证中间件,如下所示:
api.POST("/user.save", auth(true), user.Save())
api.POST("/user.somethingElse", auth(false), user.SomethingElse())
func auth(isUserSave bool) gin.HandlerFunc {
return func(c *gin.Context) {
if isUserSave {
// Do your thing
}
}
}