28 lines
545 B
Go
28 lines
545 B
Go
package middleware
|
|
|
|
import (
|
|
"crypto/rand"
|
|
"encoding/hex"
|
|
|
|
"github.com/gin-gonic/gin"
|
|
)
|
|
|
|
// RequestID 为每个请求生成唯一 ID,放入 context 和响应头
|
|
func RequestID() gin.HandlerFunc {
|
|
return func(c *gin.Context) {
|
|
// 优先使用客户端传来的 X-Request-ID
|
|
id := c.GetHeader("X-Request-ID")
|
|
if id == "" {
|
|
b := make([]byte, 12)
|
|
if _, err := rand.Read(b); err == nil {
|
|
id = hex.EncodeToString(b)
|
|
} else {
|
|
id = "unknown"
|
|
}
|
|
}
|
|
c.Set("request_id", id)
|
|
c.Header("X-Request-ID", id)
|
|
c.Next()
|
|
}
|
|
}
|