douwen8424 2018-05-29 00:29
浏览 41
已采纳

Gin-Gonic中间件声明

I'm using Gin-Gonic and I'm creating a custom middleware. See: https://github.com/gin-gonic/gin#custom-middleware

Is there a reason why the middlewares in the doc are written as such:

func MyMiddleware() gin.HandlerFunc {
    return func (c *gin.Context) {
        // middleware
    }
}
r := gin.New()
r.Use(MyMiddleware())

When I could simply write it like this:

func MyMiddleware(c *gin.Context) {
    // middleware
}
r := gin.New()
r.Use(MyMiddleware)

Thanks for your help!

  • 写回答

2条回答 默认 最新

  • dtvgo28624 2018-05-29 02:31
    关注

    You can certainly just do this if you prefer it:

    func MyMiddleware(c *gin.Context) {
        // middleware
    }
    r := gin.New()
    r.Use(MyMiddleware)
    

    The most probably reason why it is suggested that you do this instead:

    func MyMiddleware() gin.HandlerFunc {
        return func (c *gin.Context) {
            // middleware
        }
    }
    r := gin.New()
    r.Use(MyMiddleware())
    

    is, so you can add parameters, the example used in here: https://github.com/gin-gonic/gin#custom-middleware is a logging middleware.:

    func Logger() gin.HandlerFunc {
        return func(c *gin.Context) {
            // code goes here
        }
    }
    

    It didn't have any params, but you can use custom logger like logrus inside your middleware by adding a param:

    You can have a logging middleware like this:

    func Logger(log *logrus.Logger) gin.HandlerFunc {
        return func(c *gin.Context) {
            // use logrus
            log.WithFields(log.Fields{
              "animal": "walrus",
            }).Info("A walrus appears")
    
        }
    }
    

    And use it like this:

    var log = logrus.New()
    r.Use(Logger(log))
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 刚接触VFP,我想知道为什么是这种情况,有人可以看看吗
  • ¥15 io.jsonwebtoken.security.Keys
  • ¥15 急,ubuntu安装后no caching mode page found等
  • ¥15 联想交换机NE2580O/NE1064TO安装SONIC
  • ¥15 防火墙的混合模式配置
  • ¥15 Ubuntu不小心注销了要怎么恢复啊
  • ¥15 win10电脑安装完plcsim advanced4.0运行时为什么会提示找不到虚拟网卡
  • ¥15 安装powerbuilder10卡在安装程序正在运行这个页面 没有下一步任何指令
  • ¥15 关于mpi的问题:请问遇到这种情况需要怎么解决,出现这个问题后电脑不能进行mpi多核运行只能进行单核运行
  • ¥50 微信聊天记录备份到电脑提示成功了,但还是没同步到电脑微信