feat: OpenAPI 契约对齐与框架优化
All checks were successful
构建并部署到测试环境(无 SSH) / build-and-deploy (push) Successful in 5m45s

主要变更:
1. OpenAPI 文档契约对齐
   - 统一错误响应字段名为 msg(非 message)
   - 规范 envelope 响应结构(code, msg, data, timestamp)
   - 个人客户路由纳入文档体系(使用 Register 机制)
   - 新增 BuildDocHandlers() 统一管理 handler 构造
   - 确保文档生成的幂等性

2. Service 层错误处理统一
   - 全面替换 fmt.Errorf 为 errors.New/Wrap
   - 统一错误码使用规范
   - Handler 层参数校验不泄露底层细节
   - 新增错误码验证集成测试

3. 代码质量提升
   - 删除未使用的 Task handler 和路由
   - 新增代码规范检查脚本(check-service-errors.sh)
   - 新增注释路径一致性检查(check-comment-paths.sh)
   - 更新 API 文档生成指南

4. OpenSpec 归档
   - 归档 openapi-contract-alignment 变更(63 tasks)
   - 归档 service-error-unify-core 变更
   - 归档 service-error-unify-support 变更
   - 归档 code-cleanup-docs-update 变更
   - 归档 handler-validation-security 变更
   - 同步 delta specs 到主规范文件

影响范围:
- pkg/openapi: 新增 handlers.go,优化 generator.go
- internal/service/*: 48 个 service 文件错误处理统一
- internal/handler/admin: 优化参数校验错误提示
- internal/routes: 个人客户路由改造,删除 task 路由
- scripts: 新增 3 个代码检查脚本
- docs: 更新 OpenAPI 文档(15750+ 行)
- openspec/specs: 同步 3 个主规范文件

破坏性变更:无
向后兼容:是
This commit is contained in:
2026-01-30 11:40:36 +08:00
parent 1290160728
commit 409a68d60b
88 changed files with 27358 additions and 990 deletions

View File

@@ -95,6 +95,17 @@ X-Request-ID: 550e8400-e29b-41d4-a716-446655440000
| 1008 | CodeTooManyRequests | 429 | 请求过多 | 触发限流 |
| 1009 | CodeRequestEntityTooLarge | 413 | 请求体过大 | 文件上传超限 |
#### 财务相关错误 (1050-1069)
| 错误码 | 名称 | HTTP 状态 | 消息 | 使用场景 |
|--------|------|-----------|------|----------|
| 1050 | CodeInvalidStatus | 400 | 状态不允许此操作 | 资源状态不允许执行当前操作 |
| 1051 | CodeInsufficientBalance | 400 | 余额不足 | 钱包余额不足以完成操作 |
| 1052 | CodeWithdrawalNotFound | 404 | 提现申请不存在 | 提现记录未找到 |
| 1053 | CodeWalletNotFound | 404 | 钱包不存在 | 钱包记录未找到 |
| 1054 | CodeInsufficientQuota | 400 | 额度不足 | 套餐分配额度不足 |
| 1055 | CodeExceedLimit | 400 | 超过限制 | 超过系统限制(如设备绑定卡数) |
### 服务端错误 (2000-2999)
| 错误码 | 名称 | HTTP 状态 | 消息 | 使用场景 |
@@ -230,6 +241,137 @@ func (h *Handler) SpecialCase(c *fiber.Ctx) error {
---
## Handler 层参数校验安全实践
### ❌ 错误示例:泄露内部细节
```go
func (h *ShopHandler) Create(c *fiber.Ctx) error {
var req dto.CreateShopRequest
// ❌ 错误:直接暴露解析错误
if err := c.BodyParser(&req); err != nil {
return errors.New(errors.CodeInvalidParam, "参数解析失败: "+err.Error())
// 可能泄露json: cannot unmarshal number into Go struct field CreateShopRequest.ShopCode of type string
}
// ❌ 错误:直接暴露 validator 错误
if err := h.validator.Struct(&req); err != nil {
return errors.New(errors.CodeInvalidParam, "参数验证失败: "+err.Error())
// 可能泄露Key: 'CreateShopRequest.ShopName' Error:Field validation for 'ShopName' failed on the 'required' tag
}
// ...
}
```
**安全风险**
- 泄露内部字段名ShopCode、ShopName
- 泄露数据类型string、number
- 泄露验证规则required、min、max 等)
- 攻击者可根据错误消息推断 API 内部结构
### ✅ 正确示例:安全的参数校验
```go
func (h *ShopHandler) Create(c *fiber.Ctx) error {
var req dto.CreateShopRequest
// ✅ 正确:通用错误消息 + 结构化日志WARN 级别)
if err := c.BodyParser(&req); err != nil {
logger.GetAppLogger().Warn("参数解析失败",
zap.String("path", c.Path()),
zap.String("method", c.Method()),
zap.Error(err),
)
return errors.New(errors.CodeInvalidParam, "请求参数格式错误")
}
// ✅ 正确:使用默认消息 + 结构化日志WARN 级别)
if err := h.validator.Struct(&req); err != nil {
logger.GetAppLogger().Warn("参数验证失败",
zap.String("path", c.Path()),
zap.String("method", c.Method()),
zap.Error(err),
)
return errors.New(errors.CodeInvalidParam) // 使用默认消息
}
// 业务逻辑...
shop, err := h.service.Create(c.UserContext(), &req)
if err != nil {
return err
}
return response.Success(c, shop)
}
```
**安全优势**
- 对外:统一返回通用消息("参数验证失败"
- 日志:记录详细错误信息用于排查
- 包含 request_id便于日志关联和问题追踪
### 单元测试示例
```go
func TestShopHandler_Create_ParamValidation(t *testing.T) {
// 准备测试环境
app := fiber.New()
handler := NewShopHandler(mockService, mockValidator, logger)
app.Post("/shops", handler.Create)
tests := []struct {
name string
requestBody string
expectedCode int
expectedMsg string
}{
{
name: "参数解析失败",
requestBody: `{"shop_code": 123}`, // 类型错误
expectedCode: errors.CodeInvalidParam,
expectedMsg: "请求参数格式错误",
},
{
name: "必填字段缺失",
requestBody: `{"shop_code": ""}`, // ShopName 缺失
expectedCode: errors.CodeInvalidParam,
expectedMsg: "参数验证失败",
},
{
name: "正常请求",
requestBody: `{"shop_code": "SH001", "shop_name": "测试店铺"}`,
expectedCode: errors.CodeSuccess,
expectedMsg: "操作成功",
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
req := httptest.NewRequest("POST", "/shops", strings.NewReader(tt.requestBody))
req.Header.Set("Content-Type", "application/json")
resp, _ := app.Test(req)
defer resp.Body.Close()
var result map[string]interface{}
json.NewDecoder(resp.Body).Decode(&result)
assert.Equal(t, tt.expectedCode, int(result["code"].(float64)))
assert.Equal(t, tt.expectedMsg, result["msg"])
// ✅ 验证:错误消息不泄露内部细节
assert.NotContains(t, result["msg"], "ShopCode")
assert.NotContains(t, result["msg"], "ShopName")
assert.NotContains(t, result["msg"], "required")
})
}
}
```
---
## 客户端错误处理
### JavaScript/TypeScript
@@ -412,14 +554,60 @@ return errors.New(errors.CodeDatabaseError, "用户名不能为空") // 应该
return errors.New(errors.CodeNotFound, "") // 应该提供具体消息
```
### 2. 错误消息编写
### 2. 参数校验安全加固(重要)
**正确示例**
```go
// 清晰、具体的错误消息
// 参数解析失败
if err := c.BodyParser(&req); err != nil {
logger.GetAppLogger().Warn("参数解析失败",
zap.String("path", c.Path()),
zap.String("method", c.Method()),
zap.Error(err),
)
return errors.New(errors.CodeInvalidParam, "请求参数格式错误")
}
// 参数验证失败
if err := h.validator.Struct(&req); err != nil {
logger.GetAppLogger().Warn("参数验证失败",
zap.String("path", c.Path()),
zap.String("method", c.Method()),
zap.Error(err),
)
return errors.New(errors.CodeInvalidParam) // 使用默认消息
}
```
**错误示例 - 泄露内部细节**
```go
// ❌ 危险:泄露 validator 规则和字段名
if err := h.validator.Struct(&req); err != nil {
return errors.New(errors.CodeInvalidParam, "参数验证失败: "+err.Error())
}
// 可能返回:"Field validation for 'Username' failed on the 'required' tag"
// ❌ 危险:泄露类型信息
if err := c.BodyParser(&req); err != nil {
return errors.New(errors.CodeInvalidParam, "参数解析失败: "+err.Error())
}
// 可能返回:"Unmarshal type error: expected=uint got=string field=shop_id"
```
**安全原则**
- 对外统一返回通用消息("参数验证失败"
- 详细错误信息仅记录到日志
- 使用 WARN 级别(客户端错误)
- 必须包含请求上下文path、method
### 3. 错误消息编写
**正确示例**
```go
// 清晰、具体的错误消息(不泄露内部细节)
errors.New(errors.CodeInvalidParam, "用户名长度必须在 3-20 个字符之间")
errors.New(errors.CodeNotFound, "用户 ID 123 不存在")
errors.New(errors.CodeConflict, "邮箱 test@example.com 已被注册")
errors.New(errors.CodeNotFound, "用户不存在")
errors.New(errors.CodeConflict, "邮箱已被注册")
```
**错误示例**
@@ -428,8 +616,9 @@ errors.New(errors.CodeConflict, "邮箱 test@example.com 已被注册")
errors.New(errors.CodeInvalidParam, "错误")
errors.New(errors.CodeNotFound, "not found")
// 不要暴露敏感信息
// 不要暴露敏感信息和内部细节
errors.New(errors.CodeDatabaseError, "SQL error: SELECT * FROM users WHERE password = '...'")
errors.New(errors.CodeInvalidParam, "Field 'Username' validation failed") // 泄露字段名
```
### 3. 错误包装
@@ -558,5 +747,140 @@ A: 堆栈跟踪仅在 panic 时记录,无法关闭。如需调整,修改 `in
---
## Service 层错误处理实战案例
### 案例 1套餐服务 - 资源查询
**场景**:获取套餐详情,需处理不存在和数据库错误
```go
// internal/service/package/service.go
func (s *Service) Get(ctx context.Context, id uint) (*dto.PackageResponse, error) {
pkg, err := s.packageStore.GetByID(ctx, id)
if err != nil {
// ✅ 业务错误:资源不存在
if err == gorm.ErrRecordNotFound {
return nil, errors.New(errors.CodeNotFound, "套餐不存在")
}
// ✅ 系统错误:数据库查询失败
return nil, errors.Wrap(errors.CodeInternalError, err, "获取套餐失败")
}
return s.toResponse(ctx, pkg), nil
}
```
**错误返回示例**
- 套餐不存在404
```json
{"code": 1006, "msg": "套餐不存在", "data": null}
```
- 数据库错误500
```json
{"code": 2001, "msg": "内部服务器错误", "data": null}
```
日志中记录详细错误:`获取套餐失败: connection refused`
### 案例 2分佣提现 - 复杂业务校验
**场景**:提现审核,需验证余额、状态等
```go
// internal/service/commission_withdrawal/service.go
func (s *Service) Approve(ctx context.Context, id uint, req *dto.ApproveWithdrawalReq) (*dto.WithdrawalApprovalResp, error) {
// ✅ 业务错误:资源不存在
withdrawal, err := s.commissionWithdrawalReqStore.GetByID(ctx, id)
if err != nil {
return nil, errors.New(errors.CodeNotFound, "提现申请不存在")
}
// ✅ 业务错误:状态不允许
if withdrawal.Status != constants.WithdrawalStatusPending {
return nil, errors.New(errors.CodeInvalidStatus, "申请状态不允许此操作")
}
// ✅ 业务错误:余额不足
wallet, err := s.walletStore.GetShopCommissionWallet(ctx, withdrawal.ShopID)
if err != nil {
return nil, errors.New(errors.CodeNotFound, "店铺佣金钱包不存在")
}
if wallet.FrozenBalance < amount {
return nil, errors.New(errors.CodeInsufficientBalance, "钱包冻结余额不足")
}
// ✅ 系统错误:事务执行失败
err = s.db.Transaction(func(tx *gorm.DB) error {
if err := s.walletStore.DeductFrozenBalanceWithTx(ctx, tx, wallet.ID, amount); err != nil {
return errors.Wrap(errors.CodeInternalError, err, "扣除冻结余额失败")
}
// ...其他事务操作
return nil
})
if err != nil {
return nil, err
}
return &dto.WithdrawalApprovalResp{...}, nil
}
```
### 案例 3店铺管理 - 重复性检查
**场景**:创建店铺,需检查代码重复和层级限制
```go
// internal/service/shop/service.go
func (s *Service) Create(ctx context.Context, req *dto.CreateShopRequest) (*dto.ShopResponse, error) {
// ✅ 业务错误:重复检查
existing, _ := s.shopStore.GetByCode(ctx, req.ShopCode)
if existing != nil {
return nil, errors.New(errors.CodeDuplicate, "店铺代码已存在")
}
// ✅ 业务错误:层级限制
level := 1
if req.ParentID != nil {
parent, err := s.shopStore.GetByID(ctx, *req.ParentID)
if err != nil {
return nil, errors.New(errors.CodeNotFound, "上级店铺不存在")
}
level = parent.Level + 1
if level > 7 {
return nil, errors.New(errors.CodeInvalidParam, "店铺层级超过限制")
}
}
// ✅ 系统错误:数据库操作
shop := &model.Shop{...}
if err := s.shopStore.Create(ctx, shop); err != nil {
return nil, errors.Wrap(errors.CodeInternalError, err, "创建店铺失败")
}
return s.toResponse(shop), nil
}
```
### 错误处理原则总结
| 场景类型 | 使用方式 | HTTP 状态码 | 示例 |
|---------|---------|-----------|------|
| 资源不存在 | `errors.New(CodeNotFound)` | 404 | 套餐、店铺、用户不存在 |
| 状态不允许 | `errors.New(CodeInvalidStatus)` | 400 | 订单已取消、提现已审核 |
| 参数错误 | `errors.New(CodeInvalidParam)` | 400 | 层级超限、金额无效 |
| 重复操作 | `errors.New(CodeDuplicate)` | 409 | 代码重复、用户名已存在 |
| 余额不足 | `errors.New(CodeInsufficientBalance)` | 400 | 钱包余额不足 |
| 数据库错误 | `errors.Wrap(CodeInternalError, err)` | 500 | 查询失败、创建失败 |
| 队列错误 | `errors.Wrap(CodeInternalError, err)` | 500 | 任务提交失败 |
**核心原则**
1. 业务错误4xx使用 `errors.New(Code4xx, msg)`
2. 系统错误5xx使用 `errors.Wrap(Code5xx, err, msg)`
3. 错误消息保持中文,便于日志排查
4. 禁止 `fmt.Errorf` 直接对外返回,避免泄露内部细节
---
**版本历史**:
- v1.1.0 (2026-01-29): 补充 Service 层错误处理实战案例
- v1.0.0 (2025-11-15): 初始版本

File diff suppressed because it is too large Load Diff

15750
docs/admin-openapi.yaml.old Normal file

File diff suppressed because it is too large Load Diff

View File

@@ -355,6 +355,65 @@ type ShopPageResult struct {
}
```
### 7. 响应 Envelope 格式
**所有 API 响应都会被自动包裹在统一的 envelope 结构中。**
OpenAPI 文档会自动为成功响应生成以下结构:
```yaml
responses:
"200":
content:
application/json:
schema:
type: object
properties:
code:
type: integer
example: 0
description: 响应码
msg:
type: string
example: success
description: 响应消息
data:
$ref: '#/components/schemas/YourDTO' # 你定义的 DTO
timestamp:
type: string
format: date-time
description: 时间戳
```
**注意事项**:
- DTO 中只需定义 `data` 字段的内容,无需定义 envelope 字段
- 错误响应使用 `msg` 字段(不是 `message`
- 删除操作等无返回数据的接口,`data` 字段为 `null`
**示例**:
```go
// DTO 定义(只定义 data 部分)
type LoginResponse struct {
Token string `json:"token" description:"访问令牌"`
Customer *PersonalCustomerDTO `json:"customer" description:"客户信息"`
}
// 实际 API 响应(自动包裹 envelope
{
"code": 0,
"msg": "success",
"data": {
"token": "eyJhbGciOiJI...",
"customer": {
"id": 1,
"phone": "13800000000"
}
},
"timestamp": "2026-01-30T10:00:00Z"
}
```
---
## 文档生成流程
@@ -544,7 +603,68 @@ Register(router, doc, basePath, "PUT", "/:id", handler.Update, RouteSpec{
grep "/api/admin/xxx" docs/admin-openapi.yaml
```
### Q5: 如何调试文档生成
### Q5: 如何为个人客户路由(/api/c/v1添加文档
个人客户路由需要在独立的路由文件中注册,并使用 `Register()` 函数以纳入 OpenAPI 文档。
**示例**`internal/routes/personal.go`
```go
func RegisterPersonalCustomerRoutes(router fiber.Router, doc *openapi.Generator, basePath string, handlers *bootstrap.Handlers, personalAuthMiddleware *middleware.PersonalAuthMiddleware) {
// 公开路由(不需要认证)
publicGroup := router.Group("")
Register(publicGroup, doc, basePath, "POST", "/login/send-code", handlers.PersonalCustomer.SendCode, RouteSpec{
Summary: "发送验证码",
Description: "向指定手机号发送登录验证码",
Tags: []string{"个人客户 - 认证"},
Auth: false,
Input: &apphandler.SendCodeRequest{},
Output: nil,
})
Register(publicGroup, doc, basePath, "POST", "/login", handlers.PersonalCustomer.Login, RouteSpec{
Summary: "手机号登录",
Description: "使用手机号和验证码登录",
Tags: []string{"个人客户 - 认证"},
Auth: false,
Input: &apphandler.LoginRequest{},
Output: &apphandler.LoginResponse{},
})
// 需要认证的路由
authGroup := router.Group("")
authGroup.Use(personalAuthMiddleware.Authenticate())
Register(authGroup, doc, basePath, "GET", "/profile", handlers.PersonalCustomer.GetProfile, RouteSpec{
Summary: "获取个人资料",
Description: "获取当前登录客户的个人资料",
Tags: []string{"个人客户 - 账户"},
Auth: true,
Input: nil,
Output: &apphandler.PersonalCustomerDTO{},
})
}
```
**在 `routes.go` 中调用**
```go
func RegisterRoutesWithDoc(app *fiber.App, handlers *bootstrap.Handlers, middlewares *bootstrap.Middlewares, doc *openapi.Generator) {
// ... 其他路由
// 个人客户路由 (挂载在 /api/c/v1)
personalGroup := app.Group("/api/c/v1")
RegisterPersonalCustomerRoutes(personalGroup, doc, "/api/c/v1", handlers, middlewares.PersonalAuth)
}
```
**关键点**
- basePath 必须是完整路径(如 `/api/c/v1`
- 需要传入 `personalAuthMiddleware` 以支持认证路由组
- Tags 使用中文并包含模块前缀(如 "个人客户 - 认证"
### Q6: 如何调试文档生成?
```bash
# 1. 查看生成的 YAML 文件

View File

@@ -19,6 +19,18 @@ Comprehensive guide for configuring and using the rate limiting middleware in Ju
The rate limiting middleware protects your API from abuse by limiting the number of requests a client can make within a specified time window. It operates at the IP address level, ensuring each client has independent rate limits.
### Coverage Scope
Rate limiting is applied to the following business API route groups:
-`/api/admin/*` - Admin management APIs
-`/api/h5/*` - H5 client APIs
-`/api/c/v1/*` - Personal customer APIs
The following routes are **explicitly excluded** from rate limiting:
-`/api/callback/*` - Third-party callback routes (payment, webhooks)
-`/health` - Health check endpoint
-`/ready` - Readiness check endpoint
### Key Features
- **IP-based rate limiting**: Each client IP has independent counters
@@ -27,6 +39,7 @@ The rate limiting middleware protects your API from abuse by limiting the number
- **Fail-safe operation**: Continues with in-memory storage if Redis fails
- **Hot-reloadable**: Change limits without restarting server
- **Unified error responses**: Returns 429 with standardized error format
- **Selective coverage**: Applied only to business API routes
### How It Works
@@ -355,27 +368,46 @@ func main() {
app := fiber.New()
// Optional: Register rate limiter middleware
// Optional: Apply rate limiter to business API route groups
if config.GetConfig().Middleware.EnableRateLimiter {
var storage fiber.Storage = nil
rateLimitMiddleware := createRateLimiter(cfg, appLogger)
// Use Redis storage if configured
if config.GetConfig().Middleware.RateLimiter.Storage == "redis" {
storage = redisStorage // Assume redisStorage is initialized
}
// Admin API group
adminGroup := app.Group("/api/admin")
adminGroup.Use(rateLimitMiddleware)
app.Use(middleware.RateLimiter(
config.GetConfig().Middleware.RateLimiter.Max,
config.GetConfig().Middleware.RateLimiter.Expiration,
storage,
))
// H5 API group
h5Group := app.Group("/api/h5")
h5Group.Use(rateLimitMiddleware)
// Personal customer API group
personalGroup := app.Group("/api/c/v1")
personalGroup.Use(rateLimitMiddleware)
}
// Register routes
app.Get("/api/v1/users", listUsersHandler)
// Health check (excluded from rate limiting)
app.Get("/health", healthHandler)
// Callback routes (excluded from rate limiting)
callbackGroup := app.Group("/api/callback")
callbackGroup.Post("/payment", paymentCallbackHandler)
app.Listen(":3000")
}
func createRateLimiter(cfg *config.Config, logger *zap.Logger) fiber.Handler {
var storage fiber.Storage = nil
if cfg.Middleware.RateLimiter.Storage == "redis" {
storage = middleware.NewRedisStorage(/* ... */)
}
return middleware.RateLimiter(
cfg.Middleware.RateLimiter.Max,
cfg.Middleware.RateLimiter.Expiration,
storage,
)
}
```
### Custom Rate Limiter (Different Limits for Different Routes)
@@ -402,14 +434,19 @@ adminAPI.Post("/users", createUserHandler)
### Bypassing Rate Limiter for Specific Routes
```go
// Apply rate limiter globally
app.Use(middleware.RateLimiter(100, 1*time.Minute, nil))
// Apply rate limiter to specific route groups only
rateLimitMiddleware := middleware.RateLimiter(100, 1*time.Minute, nil)
// But register health check BEFORE rate limiter
// Business API routes (rate limited)
adminGroup := app.Group("/api/admin")
adminGroup.Use(rateLimitMiddleware)
// Health check (excluded from rate limiting)
app.Get("/health", healthHandler) // Not rate limited
// Alternative: Register after but add skip logic in middleware
// (requires custom middleware modification)
// Callback routes (excluded from rate limiting)
callbackGroup := app.Group("/api/callback")
callbackGroup.Post("/payment", paymentCallbackHandler) // Not rate limited
```
### Testing Rate Limiter in Code