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 DS18B20内部ADC模数转换器
  • ¥15 做个有关计算的小程序
  • ¥15 MPI读取tif文件无法正常给各进程分配路径
  • ¥15 如何用MATLAB实现以下三个公式(有相互嵌套)
  • ¥30 关于#算法#的问题:运用EViews第九版本进行一系列计量经济学的时间数列数据回归分析预测问题 求各位帮我解答一下
  • ¥15 setInterval 页面闪烁,怎么解决
  • ¥15 如何让企业微信机器人实现消息汇总整合
  • ¥50 关于#ui#的问题:做yolov8的ui界面出现的问题
  • ¥15 如何用Python爬取各高校教师公开的教育和工作经历
  • ¥15 TLE9879QXA40 电机驱动