一般使用方法是作为gin中间件

r := gin.New()
r.Use(requestid.New())

源码:检查请求头X-Request-ID(可自定)的值,如无,则以uuid方式(可自定)生成

func New(opts ...Option) gin.HandlerFunc {
    cfg := &config{
        generator: func() string {
            return uuid.New().String()
        },
        headerKey: "X-Request-ID",
    }

    for _, opt := range opts {
        opt(cfg)
    }

    headerXRequestID = string(cfg.headerKey)

    return func(c *gin.Context) {
        // Get id from request
        rid := c.GetHeader(headerXRequestID)
        if rid == "" {
            rid = cfg.generator()
            c.Request.Header.Add(headerXRequestID, rid)
        }
        if cfg.handler != nil {
            cfg.handler(c, rid)
        }
        // Set the id to ensure that the requestid is in the response
        c.Header(headerXRequestID, rid)
        c.Next()
    }
}

在gin请求日志中打印requestid

router.Use(func(c *gin.Context) {
    // ...
    c.Next()

    logrus.WithFields(logrus.Fields{
        // ..
        "status_code": c.Writer.Status(),
        "req_id":      requestid.Get(c),
    }).Info()
})

在响应体插入requestid

func resp(c *gin.Context, status int, code int, msg string, data interface{}) {
    resp := bo.ApiResp{
        Status:  status,
        Code:    code,
        Message: msg,
        ReqId:   requestid.Get(c),
        Data:    data,
    }
    c.JSON(status, resp)
}