4.2 KiB
4.2 KiB
CLAUDE.md
This file provides guidance to Claude Code (claude.ai/code) when working with code in this repository.
项目概述
基于 Rust + Axum 的配置驱动型 Mock 服务。在 mocks/ 目录下通过 YAML 文件定义 API 行为,无需修改代码即可添加/修改接口。
核心特性:
- YAML 驱动的请求匹配(method、path、query_params、headers、body)
- 热重载:
mocks/*.yaml变更自动生效,无需重启服务 - 大文件流式响应:通过
file://协议从磁盘流式读取 - 文件上传端点:
POST /api/upload
构建与测试命令
cargo build # 构建项目
cargo run # 启动服务 http://127.0.0.1:8080
cargo test # 运行所有测试
cargo test <pattern> # 运行匹配的测试(如 `cargo test router`)
cargo clippy # 代码检查
cargo fmt # 格式化代码
架构
┌─────────────┐ ┌──────────────┐ ┌────────────────┐
│ loader.rs │───▶│ router.rs │───▶│ handler.rs │
│ YAML → 索引 │ │ HashMap 索引 │ │ 请求/响应处理 │
└─────────────┘ └──────────────┘ └────────────────┘
▲ │
│ ┌──────────────────┐ │
└─────────│ main.rs │◀─────────┘
热重载 │ AppState(RwLock)│
└──────────────────┘
数据流:
MockLoader扫描mocks/目录,解析 YAML 为MockRule结构体- 规则按路径首段建立索引(如
/api/users→ key:api)存储于MockRouter - 请求匹配顺序:method → path → query_params → headers → body
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 配置示例
单接口模式:
id: "login"
request:
method: "POST"
path: "/api/login"
body: { "username": "test" }
response:
status: 200
body: '{"token": "xxx"}'
settings:
delay_ms: 100
多接口模式(数组):
- id: "get-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}' }
文件响应模式:
response:
body: "file://./data/large-file.pdf"
文件结构
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 分目录)
开发注意事项
- Rust Edition 2024,Axum 0.8.8
- 测试使用
tempfilecrate 处理临时文件 - 请求体大小限制:10MB (handler.rs:30)
- 热重载防抖时间:200ms (main.rs:46)
- Header 匹配大小写不敏感 (router.rs:75)