refactor: 统一错误消息数据源,优化错误码与映射表管理
All checks were successful
构建并部署到测试环境(无 SSH) / build-and-deploy (push) Successful in 4m36s

主要改动:
- 改造 errors.New() 和 Wrap() 函数签名为可变参数,优先使用 errorMessages 映射表
- 添加 allErrorCodes 注册表和 init() 启动时校验,确保错误码与映射表一致
- 添加 TestAllCodesHaveMessages 和 TestNoOrphanMessages 测试防止映射表腐化
- 清理 109 处与映射表一致的冗余硬编码(service 层)
- 保留业务特定消息覆盖能力

新增 API 用法:
- errors.New(errors.CodeUnauthorized) // 使用映射表默认消息
- errors.New(errors.CodeNotFound, "提现申请不存在") // 覆盖为自定义消息
This commit is contained in:
2026-01-22 18:27:42 +08:00
parent b68e7ec013
commit 6821e5abcf
28 changed files with 665 additions and 81 deletions

View File

@@ -452,13 +452,13 @@ junhong_cmp_fiber/
│ (访问日志) │
└────────────┬────────────┘
┌────────────▼────────────┐
│ 4. KeyAuth 中间件
│ (认证) │ ─── 可选 (config: enable_auth)
└────────────┬────────────┘
┌────────────▼────────────┐
│ 5. RateLimiter 中间件 │
┌────────────▼────────────┐
│ 4. 认证中间件
│ (按路由组配置) │ ─── 模块化路由注册
└────────────┬────────────┘
┌────────────▼────────────┐
│ 5. RateLimiter 中间件 │
│ (限流) │ ─── 可选 (config: enable_rate_limiter)
└────────────┬────────────┘
@@ -502,20 +502,22 @@ junhong_cmp_fiber/
- **始终激活**:是
- **日志格式**:包含字段的 JSONtimestamp、level、method、path、status、duration_ms、request_id、ip、user_agent、user_id
#### 4. KeyAuth 中间件(internal/middleware/auth.go
#### 4. 认证中间件pkg/middleware/auth.go 和 internal/middleware/
- **用途**:使用 Token 验证对请求进行认证
- **行为**
-`token` 请求头提取 token
- 通过 Redis 验证 token`auth:token:{token}`
-`Authorization: Bearer {token}` 请求头提取 token
- 通过 TokenValidator 函数验证 token支持 JWT 和 Redis Token
- 如果缺失/无效 token 返回 401
- 如果 Redis 不可用返回 503fail-closed 策略
- 成功时将用户 ID 存储在上下文中:`c.Locals(constants.ContextKeyUserID)`
- **配置**`middleware.enable_auth`默认true
- **跳过路由**`/health`(健康检查绕过认证
- 成功时将用户信息存储在上下文中UserID、UserType、ShopID、EnterpriseID
- **实现方式**:模块化路由注册(无全局配置)
- `/api/admin/*`后台认证SuperAdmin、Platform、Agent
- `/api/h5/*`H5 认证Agent、Enterprise
- `/api/personal/*`个人客户认证JWT
- **跳过路由**:各路由组可自行配置跳过路径(如 `/api/admin/login`
- **错误码**
- 1001缺失 token
- 1002无效或过期 token
- 1004认证服务不可用
- 1003权限不足
#### 5. RateLimiter 中间件internal/middleware/ratelimit.go
- **用途**:通过限制请求速率保护 API 免受滥用
@@ -545,11 +547,8 @@ app.Use(recover.New())
app.Use(addRequestID())
app.Use(loggerMiddleware())
// 可选:认证中间件
if config.GetConfig().Middleware.EnableAuth {
tokenValidator := validator.NewTokenValidator(rdb, logger.GetAppLogger())
app.Use(middleware.KeyAuth(tokenValidator, logger.GetAppLogger()))
}
// 模块化路由注册(认证中间件按路由组配置)
routes.RegisterRoutes(app, handlers, middlewares)
// 可选:限流中间件
if config.GetConfig().Middleware.EnableRateLimiter {
@@ -557,16 +556,13 @@ if config.GetConfig().Middleware.EnableRateLimiter {
if config.GetConfig().Middleware.RateLimiter.Storage == "redis" {
storage = redisStorage // 使用 Redis 存储
}
app.Use(middleware.RateLimiter(
v1 := app.Group("/api/v1")
v1.Use(middleware.RateLimiter(
config.GetConfig().Middleware.RateLimiter.Max,
config.GetConfig().Middleware.RateLimiter.Expiration,
storage,
))
}
// 路由
app.Get("/health", healthHandler)
app.Get("/api/v1/users", listUsersHandler)
```
### 请求流程示例