我的Golang API中有user.save
路径(下方)可用于create
和update
用户,具体取决于是否在{1}}中提供了id
请求对象。该路由使用其他路由也使用的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
并确定是否继续或返回。
答案 0 :(得分:4)
您可以检查身份验证处理程序中的网址。实际的请求是在上下文中,所以它很简单:
if c.Request.URL.Path == "/user.save" {
// Do your thing
}
另一种解决方案是参数化您的auth中间件,如下所示:
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
}
}
}