当前位置:  开发笔记 > 编程语言 > 正文

Accessing route in middleware using Gin

如何解决《AccessingrouteinmiddlewareusingGin》经验,为你挑选了1个好方法。

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> Alex Guerra..:

您可以从auth处理程序中检查网址。实际的请求是在上下文中进行的,因此很简单:

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

推荐阅读
重庆制造漫画社
这个屌丝很懒,什么也没留下!
DevBox开发工具箱 | 专业的在线开发工具网站    京公网安备 11010802040832号  |  京ICP备19059560号-6
Copyright © 1998 - 2020 DevBox.CN. All Rights Reserved devBox.cn 开发工具箱 版权所有