使用Gin中间件访问路由

huangapple go评论82阅读模式
英文:

Accessing route in middleware using Gin

问题

我有一个在我的 Golang API 中的 user.save 路由(如下所示),可以根据请求对象中是否提供了 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) {
        // 我想在这里知道是否调用了 user.save 路由
        // 进行身份验证操作
    }
}

我在考虑,如果我能在 auth 中间件中检测到是否调用了 user.save 路由,那么我就可以检查是否包含了 id,并决定是继续执行还是返回。

英文:

I have a user.save route (below) in my Golang API that can be used to create and update a user depending on whether an id was provided in the request object. The route uses the auth middleware which other routes do too.

api.POST("/user.save", auth(), user.Save())
api.POST("/user.somethingElse", auth(), user.SomethingElse())

Here is my middleware:

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
    }
}

I'm thinking that if I can detect in the auth middleware whether the user.save route was called I can then check to see if an id was included and decide whether to continue or return.

答案1

得分: 8

你可以从授权处理程序中检查URL。实际请求在上下文中,所以很容易实现:

if c.Request.URL.Path == "/user.save" {
    // 做你的事情
}

另一种解决方案是将授权中间件参数化,类似于这样:

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 {
            // 做你的事情
        }
    }
}
英文:

You could check the url from the auth handler. The actual request is on the context, so it's as easy as:

if c.Request.URL.Path == "/user.save" {
    // Do your thing
}

Another solution is to parameterize your auth middleware, something like this:

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
        }
    }
}

huangapple
  • 本文由 发表于 2015年12月24日 00:48:14
  • 转载请务必保留本文链接:https://go.coder-hub.com/34440246.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定