# api **Repository Path**: yangprivate_88/api ## Basic Information - **Project Name**: api - **Description**: No description available - **Primary Language**: Unknown - **License**: MIT - **Default Branch**: master - **Homepage**: None - **GVP Project**: No ## Statistics - **Stars**: 0 - **Forks**: 0 - **Created**: 2025-12-14 - **Last Updated**: 2025-12-15 ## Categories & Tags **Categories**: Uncategorized **Tags**: None ## README # Rust API 项目 基于 Axum 框架的现代化 Rust API 接口项目。 ## 特性 - ✨ 使用 Axum 0.7 框架,性能优异 - 🚀 完整的异步运行时支持 (Tokio) - 📝 结构化日志记录 (Tracing) - 🔒 类型安全的错误处理 - 🌐 CORS 支持 - 🔍 请求 ID 追踪中间件 - 📦 统一的 API 响应格式 - 🧪 单元测试示例 ## 项目结构 ``` api/ ├── src/ │ ├── main.rs # 应用入口 │ ├── error.rs # 错误处理 │ ├── middleware/ # 中间件 │ │ ├── mod.rs │ │ └── request_id.rs # 请求 ID 中间件 │ ├── models/ # 数据模型 │ │ ├── mod.rs │ │ └── response.rs # 响应模型 │ └── routes/ # 路由 │ ├── mod.rs │ ├── health.rs # 健康检查 │ └── api.rs # API 路由 ├── Cargo.toml ├── .env.example └── .gitignore ``` ## 快速开始 ### 前置要求 - Rust 1.75+ - Cargo ### 安装依赖 ```bash cargo build ``` ### 配置环境变量 复制 `.env.example` 到 `.env`: ```bash cp .env.example .env ``` ### 运行项目 开发模式: ```bash cargo run ``` 发布模式: ```bash cargo run --release ``` 服务器将在 `http://0.0.0.0:3000` 启动。 ## API 端点 ### 健康检查 ```http GET /health ``` 响应示例: ```json { "status": "ok", "timestamp": "2024-01-01T00:00:00Z", "version": "0.1.0" } ``` ### 用户管理 #### 获取用户列表 ```http GET /api/users?page=1&page_size=10 ``` #### 获取单个用户 ```http GET /api/users/:id ``` #### 创建用户 ```http POST /api/users Content-Type: application/json { "name": "张三", "email": "zhangsan@example.com" } ``` #### 更新用户 ```http PUT /api/users/:id Content-Type: application/json { "name": "李四", "email": "lisi@example.com" } ``` #### 删除用户 ```http DELETE /api/users/:id ``` ## 测试 运行测试: ```bash cargo test ``` 运行测试并显示输出: ```bash cargo test -- --nocapture ``` ## 开发指南 ### 添加新的路由 1. 在 `src/routes/` 目录下创建新的路由模块 2. 在 `src/routes/mod.rs` 中导出模块 3. 在 `src/main.rs` 中注册路由 ### 添加新的中间件 1. 在 `src/middleware/` 目录下创建新的中间件 2. 在 `src/middleware/mod.rs` 中导出 3. 在 `src/main.rs` 中应用中间件 ### 错误处理 使用 `AppError` 枚举处理错误,支持自动转换为 HTTP 响应: ```rust use crate::error::{AppError, Result}; async fn handler() -> Result>> { // 返回错误 Err(AppError::NotFound("资源未找到".to_string())) } ``` ## 环境变量 | 变量 | 说明 | 默认值 | |------|------|--------| | PORT | 服务器端口 | 3000 | | RUST_LOG | 日志级别 | api=debug,tower_http=debug | ## 性能优化 - 使用 `--release` 模式编译 - 启用 LTO (Link Time Optimization) - 使用连接池管理数据库连接 - 合理配置 Tokio 运行时 ## 部署 ### 使用 Docker ```dockerfile FROM rust:1.75 as builder WORKDIR /app COPY . . RUN cargo build --release FROM debian:bookworm-slim COPY --from=builder /app/target/release/api /usr/local/bin/api CMD ["api"] ``` ### 直接部署 ```bash cargo build --release ./target/release/api ``` ## 许可证 MIT License ## 贡献 欢迎提交 Issue 和 Pull Request!