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

报告相同问题?

悬赏问题

  • ¥30 关于#opencv#的问题:使用大疆无人机拍摄水稻田间图像,拼接成tif图片,用什么方法可以识别并框选出水稻作物行
  • ¥15 Python卡尔曼滤波融合
  • ¥20 iOS绕地区网络检测
  • ¥15 python验证码滑块图像识别
  • ¥15 根据背景及设计要求撰写设计报告
  • ¥20 能提供一下思路或者代码吗
  • ¥15 用twincat控制!
  • ¥15 请问一下这个运行结果是怎么来的
  • ¥15 单通道放大电路的工作原理
  • ¥30 YOLO检测微调结果p为1