golang常用代码片段--定制化gin中间件

limiter限流器中间件

  • 作为gin中的一个中间件,起到对接口限流的作用
  • 接口限流的配置组件每个人都不同,使用自己的就可以,本文使用的之前文章中的myConf
func MyLimiter(c *gin.Context) {
    url := c.Request.URL.Path
    if limiter := myConf.GetLimiterByUrl(url); limiter != nil && !limiter.Allow() {
        myLog.GetUidTraceLog(c).Errorf("limit url: [%s]", url)
        c.AbortWithStatus(http.StatusForbidden)
        return
    }
    c.Next()
}

logger记录整体请求信息的中间件,并且传入和uid绑定的logger

func MyLogger(c *gin.Context) {
    start := time.Now()
    traceLog := logrus.WithField("uid", c.Query("uid"))
    c.Set("traceLog", traceLog)
    c.Next()
    rawQuery := ""
    if c.Request.URL.RawQuery != "" {
        rawQuery = "?" + c.Request.URL.RawQuery
    }
    traceLog.WithFields(logrus.Fields{
        "remoteIp": c.ClientIP(),
        "method":   c.Request.Method,
        "url":      c.Request.URL.Path + rawQuery,
        "status":   c.Writer.Status(),
        "cost":     fmt.Sprintf("%dms", time.Since(start).Milliseconds()),
    }).Info("total log")
}

panic恢复中间件

func MyRecover(c *gin.Context) {
    defer func() {
        if err := recover(); err != nil {
            myLog.GetUidTraceLog(c).Errorf("unknown panic: [%s], stacktrace: [%s]", err, debug.Stack())
            c.AbortWithStatus(http.StatusInternalServerError)
        }
    }()
    c.Next()
}

你可能感兴趣的:(golang常用代码片段--定制化gin中间件)