修复日志中间件的 UserID 类型转换 panic 问题
All checks were successful
构建并部署到测试环境(无 SSH) / build-and-deploy (push) Successful in 4m31s
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:
@@ -1,6 +1,8 @@
|
||||
package errors
|
||||
|
||||
import (
|
||||
"strconv"
|
||||
|
||||
"github.com/gofiber/fiber/v2"
|
||||
"go.uber.org/zap"
|
||||
|
||||
@@ -44,8 +46,8 @@ func FromFiberContext(c *fiber.Ctx) *ErrorContext {
|
||||
|
||||
// 提取 User ID(如果已认证)
|
||||
if uid := c.Locals(constants.ContextKeyUserID); uid != nil {
|
||||
if userID, ok := uid.(string); ok {
|
||||
ctx.UserID = userID
|
||||
if userID, ok := uid.(uint); ok {
|
||||
ctx.UserID = strconv.FormatUint(uint64(userID), 10)
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -54,9 +54,11 @@ func Middleware() fiber.Handler {
|
||||
}
|
||||
|
||||
// 获取用户 ID(由 auth 中间件设置)
|
||||
userID := ""
|
||||
var userID uint
|
||||
if uid := c.Locals(constants.ContextKeyUserID); uid != nil {
|
||||
userID = uid.(string)
|
||||
if id, ok := uid.(uint); ok {
|
||||
userID = id
|
||||
}
|
||||
}
|
||||
|
||||
// 获取响应 body
|
||||
@@ -73,7 +75,7 @@ func Middleware() fiber.Handler {
|
||||
zap.String("request_id", requestID),
|
||||
zap.String("ip", c.IP()),
|
||||
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("response_body", responseBody),
|
||||
)
|
||||
|
||||
Reference in New Issue
Block a user