From 76ca8680389f8fc705f31314d44ca833781b0cf0 Mon Sep 17 00:00:00 2001 From: CNWei Date: Sun, 22 Mar 2026 21:46:22 +0800 Subject: [PATCH] =?UTF-8?q?feat:=20=E4=BC=98=E5=8C=96CLAUDE.md?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - 优化 优化CLAUDE.md --- CLAUDE.md | 275 ++++++++++++++++-------------------------------------- 1 file changed, 82 insertions(+), 193 deletions(-) diff --git a/CLAUDE.md b/CLAUDE.md index e1370d5..b349d46 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -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 -# 构建项目 -cargo build - -# 运行项目 -cargo run - -# 运行所有测试 -cargo test - -# 运行特定测试 -cargo test test_name - -# 检查代码 -cargo check - -# 格式化代码 -cargo fmt - -# 代码检查 -cargo clippy +cargo build # 构建项目 +cargo run # 启动服务 http://127.0.0.1:8080 +cargo test # 运行所有测试 +cargo test # 运行匹配的测试(如 `cargo test router`) +cargo clippy # 代码检查 +cargo fmt # 格式化代码 ``` +## 架构 + +``` +┌─────────────┐ ┌──────────────┐ ┌────────────────┐ +│ 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 -id: "user-login" +id: "login" request: method: "POST" - path: "/api/v1/login" - query_params: - redirect: "/dashboard" - headers: - Content-Type: "application/json" - body: - username: "test" - password: "123456" + path: "/api/login" + body: { "username": "test" } response: status: 200 - headers: - Content-Type: "application/json" - body: '{"code": 0, "message": "success", "data": {"token": "xxx"}}' + body: '{"token": "xxx"}' settings: delay_ms: 100 ``` -### 多接口模式 - +**多接口模式(数组):** ```yaml - id: "get-users" - request: - method: "GET" - path: "/api/users" - response: - status: 200 - body: '{"users": []}' + request: { method: "GET", path: "/api/users" } + response: { status: 200, body: '{"users": []}' } - id: "create-user" - request: - method: "POST" - path: "/api/users" - response: - status: 201 - body: '{"id": 1}' + request: { method: "POST", path: "/api/users" } + response: { status: 201, body: '{"id": 1}' } ``` -### 文件响应模式 - +**文件响应模式:** ```yaml -id: "download-file" -request: - method: "GET" - path: "/api/download" response: - status: 200 - headers: - Content-Type: "application/pdf" - body: "file://./data/document.pdf" + body: "file://./data/large-file.pdf" ``` -## 开发规范 - -### 代码风格 - -- 使用 Rust 标准命名约定:snake_case for functions/variables, PascalCase for types -- 公开函数添加文档注释 `///` -- 错误处理使用 `Result` 和 `Option` -- 异步函数使用 `async/await` - -### 测试规范 - -- 每个模块对应一个测试文件 -- 测试函数命名:`test_<模块>_<场景>` -- 使用 `tempfile` crate 处理临时文件 -- 测试应该独立运行,不依赖执行顺序 - -### Git 提交规范 +## 文件结构 ``` -feat: 新功能 -fix: 修复 bug -docs: 文档更新 -test: 测试相关 -refactor: 代码重构 -chore: 构建/工具变更 +src/ +├── main.rs # 入口,热重载监听,Axum 路由配置 +├── config.rs # 数据结构定义(MockRule, RequestMatcher 等) +├── loader.rs # YAML 解析,目录扫描 +├── router.rs # 路径首段索引,匹配逻辑 +├── handler.rs # 统一请求处理器,文件流式响应 +└── upload.rs # Multipart 文件上传处理 + +tests/ # 集成测试(每个模块一个测试文件) +mocks/ # YAML Mock 配置文件 +storage/ # 上传文件存储(按 YYYY-MM-DD 分目录) ``` -## API 端点 +## 开发注意事项 -| 端点 | 方法 | 说明 | -|------|------|------| -| `/api/upload` | POST | 文件上传 | -| `/*` | ANY | Mock 请求处理(由 YAML 配置定义) | - -## 文件上传响应格式 - -```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 +- **Rust Edition 2024**,Axum 0.8.8 +- 测试使用 `tempfile` crate 处理临时文件 +- 请求体大小限制:10MB (handler.rs:30) +- 热重载防抖时间:200ms (main.rs:46) +- Header 匹配大小写不敏感 (router.rs:75)