- 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
37 lines
880 B
Go
37 lines
880 B
Go
package middleware
|
|
|
|
import (
|
|
"net/http"
|
|
"runtime/debug"
|
|
|
|
"github.com/echochat/backend/pkg/logs"
|
|
"github.com/echochat/backend/pkg/utils"
|
|
"github.com/gin-gonic/gin"
|
|
"go.uber.org/zap"
|
|
)
|
|
|
|
// Recovery Panic 恢复中间件
|
|
// 捕获 panic 后记录 ERROR 日志含堆栈信息,返回 500 响应
|
|
func Recovery() gin.HandlerFunc {
|
|
return func(c *gin.Context) {
|
|
defer func() {
|
|
if r := recover(); r != nil {
|
|
ctx := c.Request.Context()
|
|
logs.Error(ctx, "middleware.Recovery", "服务发生 panic",
|
|
zap.Any("error", r),
|
|
zap.String("stack", string(debug.Stack())),
|
|
zap.String("path", c.Request.URL.Path),
|
|
zap.String("method", c.Request.Method),
|
|
)
|
|
|
|
c.AbortWithStatusJSON(http.StatusInternalServerError, utils.Response{
|
|
Code: 500,
|
|
Message: "服务内部错误",
|
|
TraceID: logs.GetTraceID(ctx),
|
|
})
|
|
}
|
|
}()
|
|
c.Next()
|
|
}
|
|
}
|