跨域
All checks were successful
构建并部署到测试环境(无 SSH) / build-and-deploy (push) Successful in 7m59s

This commit is contained in:
2026-05-07 16:28:23 +08:00
parent 573e887ca5
commit 73a3a04204
18 changed files with 634 additions and 894 deletions

View File

@@ -489,17 +489,22 @@ junhong_cmp_fiber/
└────────────┬────────────┘
┌────────────▼────────────┐
│ 4. 认证中间件
│ 4. CORS 中间件 │
│ (跨域预检) │
└────────────┬────────────┘
┌────────────▼────────────┐
│ 5. 认证中间件 │
│ (按路由组配置) │ ─── 模块化路由注册
└────────────┬────────────┘
┌────────────▼────────────┐
5. RateLimiter 中间件 │
6. RateLimiter 中间件 │
│ (限流) │ ─── 可选 (config: enable_rate_limiter)
└────────────┬────────────┘
┌────────────▼────────────┐
6. 路由处理器 │
7. 路由处理器 │
│ (业务逻辑) │
└────────────┬────────────┘
@@ -538,12 +543,22 @@ junhong_cmp_fiber/
- **始终激活**:是
- **日志格式**:包含字段的 JSONtimestamp、level、method、path、status、duration_ms、request_id、ip、user_agent、user_id
#### 4. 认证中间件pkg/middleware/auth.go 和 internal/middleware/
#### 4. CORS 中间件Fiber cors
- **用途**:允许已配置前端域名跨域访问 API
- **行为**
- 对浏览器预检 `OPTIONS` 请求返回 204
- 添加 `Access-Control-Allow-Origin``Access-Control-Allow-Methods``Access-Control-Allow-Headers`
- 必须在业务路由和认证中间件之前注册,避免预检请求被 401 拦截
- **配置**`middleware.cors.*`(默认启用)
- **默认来源**`*`(全部来源)。使用通配来源时 `allow_credentials` 必须为 `false`
#### 5. 认证中间件pkg/middleware/auth.go 和 internal/middleware/
- **用途**:使用 Token 验证对请求进行认证
- **行为**
-`Authorization: Bearer {token}` 请求头提取 token
- 通过 TokenValidator 函数验证 token支持 JWT 和 Redis Token
- 如果缺失/无效 token 返回 401
- `OPTIONS` 预检请求直接返回 204不做 Token 校验
- 成功时将用户信息存储在上下文中UserID、UserType、ShopID、EnterpriseID
- **实现方式**:模块化路由注册(无全局配置)
- `/api/admin/*`后台认证SuperAdmin、Platform、Agent
@@ -555,7 +570,7 @@ junhong_cmp_fiber/
- 1002无效或过期 token
- 1003权限不足
#### 5. RateLimiter 中间件internal/middleware/ratelimit.go
#### 6. RateLimiter 中间件internal/middleware/ratelimit.go
- **用途**:通过限制请求速率保护 API 免受滥用
- **行为**
- 按客户端 IP 地址追踪请求
@@ -568,7 +583,7 @@ junhong_cmp_fiber/
- `redis`:基于 Redis分布式持久化
- **错误码**1003请求过于频繁
#### 6. 路由处理器
#### 7. 路由处理器
- **用途**:执行端点的业务逻辑
- **可用上下文数据**
- 请求 ID`c.Locals(constants.ContextKeyRequestID)`
@@ -582,6 +597,12 @@ junhong_cmp_fiber/
app.Use(recover.New())
app.Use(addRequestID())
app.Use(loggerMiddleware())
app.Use(cors.New(cors.Config{
AllowOrigins: config.GetConfig().Middleware.CORS.AllowOrigins,
AllowMethods: config.GetConfig().Middleware.CORS.AllowMethods,
AllowHeaders: config.GetConfig().Middleware.CORS.AllowHeaders,
AllowCredentials: config.GetConfig().Middleware.CORS.AllowCredentials,
}))
// 模块化路由注册(认证中间件按路由组配置)
routes.RegisterRoutes(app, handlers, middlewares)