douben6670 2015-12-23 16:48
浏览 288
已采纳

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

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条回答 默认 最新

  • duanli8391 2015-12-23 19:08
    关注

    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
            }
        }
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 计组这些题应该咋做呀
  • ¥60 更换迈创SOL6M4AE卡的时候,驱动要重新装才能使用,怎么解决?
  • ¥15 让node服务器有自动加载文件的功能
  • ¥15 jmeter脚本回放有的是对的有的是错的
  • ¥15 r语言蛋白组学相关问题
  • ¥15 Python时间序列如何拟合疏系数模型
  • ¥15 求学软件的前人们指明方向🥺
  • ¥50 如何增强飞上天的树莓派的热点信号强度,以使得笔记本可以在地面实现远程桌面连接
  • ¥20 双层网络上信息-疾病传播
  • ¥50 paddlepaddle pinn