使用Gin访问中间件中的路由

时间:2015-12-23 16:48:15

标签: go go-gin

我的Golang API中有user.save路径(下方)可用于createupdate用户,具体取决于是否在{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并确定是否继续或返回。

1 个答案:

答案 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
        }
    }
}
相关问题