feat: 实现 Gin trace 中间件生成并注入 trace ID
This commit is contained in:
17
backend/internal/trace/middleware.go
Normal file
17
backend/internal/trace/middleware.go
Normal file
@@ -0,0 +1,17 @@
|
|||||||
|
package trace
|
||||||
|
|
||||||
|
import "github.com/gin-gonic/gin"
|
||||||
|
|
||||||
|
// TraceMiddleware 为每个 HTTP 请求生成 trace ID 并注入 context
|
||||||
|
func TraceMiddleware() gin.HandlerFunc {
|
||||||
|
return func(c *gin.Context) {
|
||||||
|
traceID := GenerateTraceID()
|
||||||
|
ctx := WithTraceID(c.Request.Context(), traceID)
|
||||||
|
ctx = WithRequestID(ctx, traceID) // REST: trace_id == request_id
|
||||||
|
|
||||||
|
c.Request = c.Request.WithContext(ctx)
|
||||||
|
c.Header("X-Trace-ID", traceID) // 返回给客户端用于排查
|
||||||
|
|
||||||
|
c.Next()
|
||||||
|
}
|
||||||
|
}
|
||||||
Reference in New Issue
Block a user