Files
xlgo-core/middleware/recover.go
T
杭州明婳科技 18e4f7e891 fix: ServerConfig 加 Host 字段 + 面向用户文案统一中文
- ServerConfig 新增 Host 字段:空=监听所有接口(兼容),设值=绑定指定地址
  (127.0.0.1 仅本机 / 内网IP 绑定指定网卡),避免生产暴露 0.0.0.0
- app.go 启动地址改 host:port,日志区分"所有接口"/指定地址
- 面向用户/调用的文案统一中文:
  - middleware/recover.go: "Panic recovered"→"panic 已恢复","Panic: %v"→"服务器内部错误: %v"
  - middleware/logger.go: 5 处日志消息改中文
  - middleware/metrics.go: 3 个 Prometheus Help 改中文
  - app.go/database/manager.go/logger.go: 英文 error 改中文
- 保留英文:JSON 协议字段名、Prometheus metric Name、MySQL 错误串匹配、技术专有名词
- CLI 模板与 example 配置加 host 注释

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-23 23:12:40 +08:00

63 lines
1.7 KiB
Go

package middleware
import (
"fmt"
"net/http"
"runtime/debug"
"github.com/EthanCodeCraft/xlgo-core/logger"
"github.com/EthanCodeCraft/xlgo-core/response"
"github.com/gin-gonic/gin"
"go.uber.org/zap"
)
// Recover panic恢复中间件,捕获panic并返回统一错误响应
func Recover() gin.HandlerFunc {
return func(c *gin.Context) {
defer func() {
if err := recover(); err != nil {
// 获取请求ID
requestID := GetRequestID(c)
// 记录错误日志
logger.Error("panic 已恢复",
zap.String("request_id", requestID),
zap.String("error", fmt.Sprintf("%v", err)),
zap.String("path", c.Request.URL.Path),
zap.String("method", c.Request.Method),
zap.String("stack", string(debug.Stack())),
)
// 返回错误响应
response.FailWithCode(c, response.CodeServerError, "服务器内部错误")
c.AbortWithStatus(http.StatusInternalServerError)
}
}()
c.Next()
}
}
// RecoverWithDetail panic恢复中间件(详细版本,返回更多信息)
// 注意: 生产环境不应使用,会暴露敏感信息
func RecoverWithDetail() gin.HandlerFunc {
return func(c *gin.Context) {
defer func() {
if err := recover(); err != nil {
requestID := GetRequestID(c)
logger.Error("panic 已恢复",
zap.String("request_id", requestID),
zap.String("error", fmt.Sprintf("%v", err)),
zap.String("path", c.Request.URL.Path),
zap.String("method", c.Request.Method),
zap.String("stack", string(debug.Stack())),
)
// 开发环境返回详细错误
response.FailWithCode(c, response.CodeServerError, fmt.Sprintf("服务器内部错误: %v", err))
c.AbortWithStatus(http.StatusInternalServerError)
}
}()
c.Next()
}
}