修复日志中间件的 UserID 类型转换 panic 问题
All checks were successful
构建并部署到测试环境(无 SSH) / build-and-deploy (push) Successful in 4m31s

问题描述:
- 认证中间件存储的 UserID 是 uint 类型
- 日志中间件和错误上下文错误地将其断言为 string 类型
- 导致所有认证请求在记录访问日志时发生 panic

修复内容:
1. pkg/logger/middleware.go
   - 修改 UserID 变量类型从 string 为 uint
   - 使用安全的类型断言 (uid.(uint))
   - 使用 zap.Uint 记录日志

2. pkg/errors/context.go
   - 修改 UserID 类型断言从 string 为 uint
   - 使用 strconv.FormatUint 转换为 string 用于错误上下文

影响范围:
- 修复所有需要认证的接口的 panic 错误
- 包括 /api/admin/shops, /api/admin/me, /api/admin/permissions 等
This commit is contained in:
2026-01-21 12:17:19 +08:00
parent 9795bb9ace
commit 6f1350b527
2 changed files with 9 additions and 5 deletions

View File

@@ -1,6 +1,8 @@
package errors package errors
import ( import (
"strconv"
"github.com/gofiber/fiber/v2" "github.com/gofiber/fiber/v2"
"go.uber.org/zap" "go.uber.org/zap"
@@ -44,8 +46,8 @@ func FromFiberContext(c *fiber.Ctx) *ErrorContext {
// 提取 User ID如果已认证 // 提取 User ID如果已认证
if uid := c.Locals(constants.ContextKeyUserID); uid != nil { if uid := c.Locals(constants.ContextKeyUserID); uid != nil {
if userID, ok := uid.(string); ok { if userID, ok := uid.(uint); ok {
ctx.UserID = userID ctx.UserID = strconv.FormatUint(uint64(userID), 10)
} }
} }

View File

@@ -54,9 +54,11 @@ func Middleware() fiber.Handler {
} }
// 获取用户 ID由 auth 中间件设置) // 获取用户 ID由 auth 中间件设置)
userID := "" var userID uint
if uid := c.Locals(constants.ContextKeyUserID); uid != nil { if uid := c.Locals(constants.ContextKeyUserID); uid != nil {
userID = uid.(string) if id, ok := uid.(uint); ok {
userID = id
}
} }
// 获取响应 body // 获取响应 body
@@ -73,7 +75,7 @@ func Middleware() fiber.Handler {
zap.String("request_id", requestID), zap.String("request_id", requestID),
zap.String("ip", c.IP()), zap.String("ip", c.IP()),
zap.String("user_agent", c.Get("User-Agent")), zap.String("user_agent", c.Get("User-Agent")),
zap.String(constants.ContextKeyUserID, userID), zap.Uint("user_id", userID),
zap.String("request_body", requestBody), zap.String("request_body", requestBody),
zap.String("response_body", responseBody), zap.String("response_body", responseBody),
) )