feat: 优化CLAUDE.md

- 优化 优化CLAUDE.md
This commit is contained in:
2026-03-22 21:46:22 +08:00
parent 24c4672022
commit 76ca868038

275
CLAUDE.md
View File

@@ -1,228 +1,117 @@
# Mock Server 项目指南 # CLAUDE.md
This file provides guidance to Claude Code (claude.ai/code) when working with code in this repository.
## 项目概述 ## 项目概述
基于 Rust + Axum 的配置驱动型 Mock 服务,支持 YAML 配置、请求匹配、延迟响应、大文件流式返回和文件上传等特性 基于 Rust + Axum 的配置驱动型 Mock 服务。在 `mocks/` 目录下通过 YAML 文件定义 API 行为,无需修改代码即可添加/修改接口
## 技术栈 **核心特性:**
- YAML 驱动的请求匹配method、path、query_params、headers、body
- 热重载:`mocks/*.yaml` 变更自动生效,无需重启服务
- 大文件流式响应:通过 `file://` 协议从磁盘流式读取
- 文件上传端点:`POST /api/upload`
- **语言**: Rust (Edition 2024) ## 构建与测试命令
- **Web 框架**: Axum 0.8.8 + axum-extra (multipart 支持)
- **异步运行时**: Tokio
- **序列化**: serde + serde_yaml + serde_json
- **工具库**: walkdir, uuid, chrono, tokio-util
## 项目结构
```
mock-server/
├── src/
│ ├── main.rs # 程序入口,路由配置,服务启动
│ ├── lib.rs # 库模块导出
│ ├── config.rs # 配置结构定义 (MockRule, MockResponse, MockSettings)
│ ├── loader.rs # YAML 配置加载器,递归扫描 mocks 目录
│ ├── router.rs # 路由匹配引擎,基于路径首段索引
│ ├── handler.rs # 请求处理器,统一处理所有 Mock 请求
│ └── upload.rs # 文件上传处理模块
├── tests/ # 集成测试
│ ├── config_test.rs # 配置模块测试
│ ├── handler_test.rs # 请求处理测试
│ ├── integration_test.rs # 集成测试
│ ├── loader_test.rs # 加载器测试
│ ├── router_test.rs # 路由匹配测试
│ └── upload_test.rs # 文件上传测试
├── mocks/ # YAML Mock 配置文件目录
├── storage/ # 上传文件存储目录 (按日期分类: YYYY-MM-DD)
└── Cargo.toml
```
## 核心模块说明
### config.rs - 配置结构
定义 Mock 规则的数据结构:
- `MockRule`: 完整的 Mock 规则id, request, response, settings
- `MockRequest`: 请求匹配条件method, path, query_params, headers, body
- `MockResponse`: 响应配置status, headers, body
- `MockSettings`: 额外设置delay_ms 延迟)
- `MockSource`: 支持单接口和多接口 YAML 格式
**文件协议**: body 以 `file://` 开头时,从磁盘流式读取文件
### loader.rs - 配置加载器
- `MockLoader::load_all_from_dir()`: 递归扫描目录下的 .yaml/.yml 文件
- 按路径首段建立索引(如 `/api/users` -> key: `api`
- 支持单接口和多接口两种 YAML 格式
### router.rs - 路由匹配引擎
- 基于路径首段的 HashMap 快速索引
- 线性深度匹配method -> path -> query_params -> headers -> body
- 支持大小写不敏感的方法匹配
- 支持尾部斜杠忽略
### handler.rs - 请求处理器
- 统一处理所有 HTTP 方法和路径
- 支持延迟响应settings.delay_ms
- 支持文件流式响应(低内存占用)
- 匹配失败返回 404
### upload.rs - 文件上传
- 路由: `POST /api/upload`
- 支持 multipart/form-data 格式
- 文件存储: `storage/YYYY-MM-DD/uuid.extension`
- 返回 JSON 格式的文件信息
## 常用命令
```bash ```bash
# 构建项目 cargo build # 构建项目
cargo build cargo run # 启动服务 http://127.0.0.1:8080
cargo test # 运行所有测试
# 运行项目 cargo test <pattern> # 运行匹配的测试(如 `cargo test router`
cargo run cargo clippy # 代码检查
cargo fmt # 格式化代码
# 运行所有测试
cargo test
# 运行特定测试
cargo test test_name
# 检查代码
cargo check
# 格式化代码
cargo fmt
# 代码检查
cargo clippy
``` ```
## 架构
```
┌─────────────┐ ┌──────────────┐ ┌────────────────┐
│ loader.rs │───▶│ router.rs │───▶│ handler.rs │
│ YAML → 索引 │ │ HashMap 索引 │ │ 请求/响应处理 │
└─────────────┘ └──────────────┘ └────────────────┘
▲ │
│ ┌──────────────────┐ │
└─────────│ main.rs │◀─────────┘
热重载 │ AppState(RwLock)│
└──────────────────┘
```
**数据流:**
1. `MockLoader` 扫描 `mocks/` 目录,解析 YAML 为 `MockRule` 结构体
2. 规则按路径首段建立索引(如 `/api/users` → key: `api`)存储于 `MockRouter`
3. 请求匹配顺序method → path → query_params → headers → body
4. `AppState` 使用 `RwLock` 包装 router支持线程安全的热重载
**核心类型 (config.rs)**
- `MockRule`: 完整规则id, request, response, settings
- `RequestMatcher`: 请求匹配条件method, path, query_params, headers, body
- `MockResponse`: 响应配置status, headers, body
- `MockSource`: 枚举类型,支持单接口/多接口 YAML 格式
**请求匹配 (router.rs)**
- 路径首段 HashMap 查找O(1) 获取候选规则
- 候选集内线性扫描进行精确匹配
- Body 匹配:支持 JSON 对象和字符串两种比较方式
**响应处理 (handler.rs)**
- 内联 body直接返回
- `file://` 前缀:从磁盘流式读取文件(低内存占用)
- `settings.delay_ms`:模拟网络延迟
## YAML 配置示例 ## YAML 配置示例
### 单接口模式 **单接口模式**
```yaml ```yaml
id: "user-login" id: "login"
request: request:
method: "POST" method: "POST"
path: "/api/v1/login" path: "/api/login"
query_params: body: { "username": "test" }
redirect: "/dashboard"
headers:
Content-Type: "application/json"
body:
username: "test"
password: "123456"
response: response:
status: 200 status: 200
headers: body: '{"token": "xxx"}'
Content-Type: "application/json"
body: '{"code": 0, "message": "success", "data": {"token": "xxx"}}'
settings: settings:
delay_ms: 100 delay_ms: 100
``` ```
### 多接口模式 **多接口模式(数组):**
```yaml ```yaml
- id: "get-users" - id: "get-users"
request: request: { method: "GET", path: "/api/users" }
method: "GET" response: { status: 200, body: '{"users": []}' }
path: "/api/users"
response:
status: 200
body: '{"users": []}'
- id: "create-user" - id: "create-user"
request: request: { method: "POST", path: "/api/users" }
method: "POST" response: { status: 201, body: '{"id": 1}' }
path: "/api/users"
response:
status: 201
body: '{"id": 1}'
``` ```
### 文件响应模式 **文件响应模式**
```yaml ```yaml
id: "download-file"
request:
method: "GET"
path: "/api/download"
response: response:
status: 200 body: "file://./data/large-file.pdf"
headers:
Content-Type: "application/pdf"
body: "file://./data/document.pdf"
``` ```
## 开发规范 ## 文件结构
### 代码风格
- 使用 Rust 标准命名约定snake_case for functions/variables, PascalCase for types
- 公开函数添加文档注释 `///`
- 错误处理使用 `Result``Option`
- 异步函数使用 `async/await`
### 测试规范
- 每个模块对应一个测试文件
- 测试函数命名:`test_<模块>_<场景>`
- 使用 `tempfile` crate 处理临时文件
- 测试应该独立运行,不依赖执行顺序
### Git 提交规范
``` ```
feat: 新功能 src/
fix: 修复 bug ├── main.rs # 入口热重载监听Axum 路由配置
docs: 文档更新 ├── config.rs # 数据结构定义MockRule, RequestMatcher 等)
test: 测试相关 ├── loader.rs # YAML 解析,目录扫描
refactor: 代码重构 ├── router.rs # 路径首段索引,匹配逻辑
chore: 构建/工具变更 ├── handler.rs # 统一请求处理器,文件流式响应
└── upload.rs # Multipart 文件上传处理
tests/ # 集成测试(每个模块一个测试文件)
mocks/ # YAML Mock 配置文件
storage/ # 上传文件存储(按 YYYY-MM-DD 分目录)
``` ```
## API 端点 ## 开发注意事项
| 端点 | 方法 | 说明 | - **Rust Edition 2024**Axum 0.8.8
|------|------|------| - 测试使用 `tempfile` crate 处理临时文件
| `/api/upload` | POST | 文件上传 | - 请求体大小限制10MB (handler.rs:30)
| `/*` | ANY | Mock 请求处理(由 YAML 配置定义) | - 热重载防抖时间200ms (main.rs:46)
- Header 匹配大小写不敏感 (router.rs:75)
## 文件上传响应格式
```json
{
"success": true,
"files": [
{
"original_name": "document.pdf",
"stored_name": "550e8400-e29b-41d4-a716-446655440000.pdf",
"path": "storage/2026-03-19/550e8400-e29b-41d4-a716-446655440000.pdf",
"size": 1024,
"content_type": "application/pdf"
}
],
"message": "Files uploaded successfully"
}
```
## 扩展功能规划
- [ ] 热加载:配置文件变更自动重载
- [ ] 动态占位符:支持 `{{timestamp}}`, `{{uuid}}`
- [ ] 管理界面Web UI 管理 Mock 规则
- [ ] 请求录制:自动生成 Mock 配置
- [ ] 条件匹配:基于请求体的复杂匹配规则
## 注意事项
1. **文件协议**: 使用 `file://` 时确保文件路径正确
2. **延迟响应**: 仅用于测试,生产环境请移除
3. **上传目录**: 确保 `storage/` 目录有写入权限
4. **内存限制**: 请求体限制为 10MB