Files
EchoChat/backend/go-service/pkg/middleware/trace.go
bujinyuan c8ffbedf75 feat(backend): Go 服务骨架(配置、日志、数据库、中间件、Wire)
- config: Viper YAML 配置 + 环境变量覆盖
- logs: zap 结构化日志 + trace_id 链路追踪 + 敏感信息脱敏
- db: PostgreSQL (GORM) + Redis (go-redis) 连接管理
- middleware: Trace/Logger/CORS/Recovery 四层中间件
- provider: Wire 编译时依赖注入
- main.go: 优雅启动/关闭 HTTP 服务

Made-with: Cursor
2026-02-28 10:41:20 +08:00

27 lines
654 B
Go
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

// Package middleware 提供 Gin HTTP 中间件
package middleware
import (
"github.com/echochat/backend/pkg/logs"
"github.com/gin-gonic/gin"
)
// Trace 链路追踪中间件
// 从请求头提取 X-Request-ID不存在则自动生成
// 注入 context后续所有日志自动携带 trace_id
// 在响应头中返回 X-Request-ID
func Trace() gin.HandlerFunc {
return func(c *gin.Context) {
traceID := c.GetHeader("X-Request-ID")
if traceID == "" {
traceID = logs.GenerateTraceID()
}
ctx := logs.WithTraceID(c.Request.Context(), traceID)
c.Request = c.Request.WithContext(ctx)
c.Header("X-Request-ID", traceID)
c.Next()
}
}