24 lines
414 B
Go
24 lines
414 B
Go
package middleware
|
|
|
|
import (
|
|
"crypto/rand"
|
|
"encoding/hex"
|
|
|
|
"github.com/gin-gonic/gin"
|
|
)
|
|
|
|
// Trace 注入 trace_id 中间件
|
|
func Trace() gin.HandlerFunc {
|
|
return func(c *gin.Context) {
|
|
traceID := c.GetHeader("X-Trace-Id")
|
|
if traceID == "" {
|
|
b := make([]byte, 8)
|
|
_, _ = rand.Read(b)
|
|
traceID = hex.EncodeToString(b)
|
|
}
|
|
c.Set("trace_id", traceID)
|
|
c.Header("X-Trace-Id", traceID)
|
|
c.Next()
|
|
}
|
|
}
|