You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
gotrace_id/gin_use.go

33 lines
705 B

2 years ago
package gotrace_id
import (
2 years ago
"fmt"
2 years ago
"github.com/gin-gonic/gin"
"go.dtapp.net/gostring"
)
// SetGinTraceId 设置跟踪编号 https://www.jianshu.com/p/2a1a74ad3c3a
func SetGinTraceId() gin.HandlerFunc {
return func(c *gin.Context) {
2 months ago
requestId := c.Request.Header.Get(TraceIdRequestKey)
2 years ago
if requestId == "" {
requestId = gostring.GetUuId()
}
2 months ago
c.Set(TraceIdGinKey, requestId)
c.Writer.Header().Set(TraceIdRequestKey, requestId)
2 years ago
c.Next()
}
}
// GetGinTraceId 通过gin中间件获取跟踪编号
func GetGinTraceId(c *gin.Context) string {
2 months ago
traceId := fmt.Sprintf("%s", c.MustGet(TraceIdGinKey))
2 years ago
if traceId == Nil {
2 years ago
return ""
}
2 years ago
if len(traceId) <= 0 {
2 years ago
return ""
}
2 years ago
return traceId
2 years ago
}