补齐 HTTP 层:实现用户模块、路由与中间件接线、COS 上传及优雅启动
- 新增用户与上传错误码文件及 Recovery 中间件 - 修复 router.go 导入与中间件链,注册用户路由并补 handler 错误码导入 - 补充用户状态常量与 UserGetByWechatOpenID 查询,修订刷新令牌 dto - 移除 upload 包 OTel 调用,新增 FileUploadCos 上传封装 - 实现 UserService 微信登录/刷新令牌/我的信息/改资料/上传头像 - 裁剪 main.go 配置段并移除 OTel 桥接,补启动与优雅退出 - 新增 configs 示例配置、global 配置结构及 go.mod 依赖
This commit is contained in:
@@ -0,0 +1,53 @@
|
||||
package middleware
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"fmt"
|
||||
"log/slog"
|
||||
"net"
|
||||
"net/http"
|
||||
"os"
|
||||
"runtime/debug"
|
||||
"strings"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
)
|
||||
|
||||
// Recovery 替代 gin.Recovery():panic 恢复语义保持一致(客户端断开类 panic 仅记录并中止,
|
||||
// 其余 panic 返回 500 Internal Server Error),但 panic 与堆栈统一走 slog 结构化输出,
|
||||
// 与全站 JSON 日志(含 request_id)对齐,避免默认实现写 stderr 非结构化日志。
|
||||
func Recovery() gin.HandlerFunc {
|
||||
return func(c *gin.Context) {
|
||||
defer func() {
|
||||
if r := recover(); r != nil {
|
||||
ctx := c.Request.Context()
|
||||
if isBrokenPipe(r) {
|
||||
// 连接已断开,无法再写响应:仅记录并中止。
|
||||
slog.ErrorContext(ctx, "GIN_PANIC_BROKEN_PIPE",
|
||||
"method", c.Request.Method, "path", c.Request.URL.Path, "recover", fmt.Sprint(r))
|
||||
c.Abort()
|
||||
return
|
||||
}
|
||||
slog.ErrorContext(ctx, "GIN_PANIC",
|
||||
"method", c.Request.Method, "path", c.Request.URL.Path, "ip", c.ClientIP(),
|
||||
"recover", fmt.Sprint(r), "stack", string(debug.Stack()))
|
||||
c.AbortWithStatus(http.StatusInternalServerError)
|
||||
}
|
||||
}()
|
||||
c.Next()
|
||||
}
|
||||
}
|
||||
|
||||
// isBrokenPipe 判定 panic 是否源于客户端断开(broken pipe / connection reset),与 gin.Recovery 判定一致。
|
||||
func isBrokenPipe(r any) bool {
|
||||
ne, ok := r.(*net.OpError)
|
||||
if !ok {
|
||||
return false
|
||||
}
|
||||
var se *os.SyscallError
|
||||
if !errors.As(ne, &se) {
|
||||
return false
|
||||
}
|
||||
seStr := strings.ToLower(se.Error())
|
||||
return strings.Contains(seStr, "broken pipe") || strings.Contains(seStr, "connection reset by peer")
|
||||
}
|
||||
Reference in New Issue
Block a user