axum-code-review
Compare original and translation side by side
🇺🇸
Original
English🇨🇳
Translation
ChineseAxum Code Review
Axum代码审查
Review Workflow
审查工作流
- Check Cargo.toml — Note axum version (0.6 vs 0.7+ have different patterns), Rust edition (2021 vs 2024), tower, tower-http features. Edition 2024 changes RPIT lifetime capture in handler return types and removes the need for in custom extractors.
async-trait - Check routing — Route organization, method routing, nested routers
- Check extractors — Order matters (body extractors must be last), correct types
- Check state — Shared state via , not global mutable state
State<T> - Check error handling — implementations, error types
IntoResponse
- 检查Cargo.toml — 记录axum版本(0.6与0.7+的模式不同)、Rust版本(2021 vs 2024)、tower、tower-http的特性。2024版本会改变处理程序返回类型中的RPIT生命周期捕获,并且自定义提取器不再需要。
async-trait - 检查路由 — 路由组织、方法路由、嵌套路由
- 检查提取器 — 顺序很重要(体提取器必须放在最后)、类型正确
- 检查状态 — 通过共享状态,而非全局可变状态
State<T> - 检查错误处理 — 实现、错误类型
IntoResponse
Output Format
输出格式
Report findings as:
text
[FILE:LINE] ISSUE_TITLE
Severity: Critical | Major | Minor | Informational
Description of the issue and why it matters.报告结果格式如下:
text
[FILE:LINE] ISSUE_TITLE
Severity: Critical | Major | Minor | Informational
Description of the issue and why it matters.Quick Reference
快速参考
| Issue Type | Reference |
|---|---|
| Route definitions, nesting, method routing | references/routing.md |
| State, Path, Query, Json, body extractors | references/extractors.md |
| Tower middleware, layers, error handling | references/middleware.md |
| 问题类型 | 参考文档 |
|---|---|
| 路由定义、嵌套、方法路由 | references/routing.md |
| State、Path、Query、Json、体提取器 | references/extractors.md |
| Tower中间件、层、错误处理 | references/middleware.md |
Review Checklist
审查清单
Routing
路由
- Routes organized by domain (nested routers for ,
/api/users)/api/orders - Fallback handlers defined for 404s
- Method routing explicit (,
.get(), not.post()with manual method matching).route() - No route conflicts (overlapping paths with different extractors)
- 路由按领域组织(为、
/api/users使用嵌套路由)/api/orders - 定义了404的回退处理程序
- 方法路由明确(使用、
.get(),而非手动匹配方法的.post()).route() - 无路由冲突(不同提取器的路径重叠)
Extractors
提取器
- Body-consuming extractors (,
Json,Form) are the LAST parameterBytes - requires
State<T>— typicallyT: Cloneor directArc<AppState>deriveClone - parameter types match the route definition
Path<T> - fields are
Query<T>for optional query params withOption#[serde(default)] - Custom extractors implement (not body) or
FromRequestParts(body)FromRequest - Edition 2024: Custom extractors use native in trait impls (no
async fnneeded for#[async_trait]/FromRequest)FromRequestParts
- 消费体的提取器(、
Json、Form)是最后一个参数Bytes - 要求
State<T>— 通常是T: Clone或直接派生Arc<AppState>Clone - 参数类型与路由定义匹配
Path<T> - 的可选查询参数字段使用
Query<T>并配合Option#[serde(default)] - 自定义提取器实现(非体)或
FromRequestParts(体)FromRequest - 2024版本:自定义提取器在 trait 实现中使用原生(
async fn/FromRequest不再需要FromRequestParts)#[async_trait]
State Management
状态管理
- Application state shared via , not global mutable statics
State<T> - Database pool in state (not created per-request)
- State contains only shared resources (pool, config, channels), not request-specific data
- derived or manually implemented on state type
Clone - Edition 2024: Shared static state uses from std (not
LazyLockoronce_cell::sync::Lazy)lazy_static!
- 应用状态通过共享,而非全局可变静态变量
State<T> - 数据库连接池在状态中(而非每次请求创建)
- 状态仅包含共享资源(连接池、配置、通道),不包含请求特定数据
- 状态类型派生或手动实现了
Clone - 2024版本:共享静态状态使用标准库的(而非
LazyLock或once_cell::sync::Lazy)lazy_static!
Error Handling
错误处理
- Handler errors implement for proper HTTP error codes
IntoResponse - Internal errors don't leak to clients (no raw error messages in 500 responses)
- Error responses use consistent format (JSON error body with code/message)
- pattern used for handlers
Result<impl IntoResponse, AppError> - Edition 2024: Handler return types capture all in-scope lifetimes by default; use
-> impl IntoResponseto opt out of capturing request lifetimes when returning owned data+ use<>
- 处理程序错误实现以返回正确的HTTP错误码
IntoResponse - 内部错误不泄露给客户端(500响应中不包含原始错误信息)
- 错误响应使用统一格式(包含代码/消息的JSON错误体)
- 处理程序使用模式
Result<impl IntoResponse, AppError> - 2024版本:处理程序返回类型默认捕获所有作用域内的生命周期;当返回自有数据时,使用
-> impl IntoResponse选择不捕获请求生命周期+ use<>
Middleware
中间件
- Tower layers applied in correct order (outer runs first on request, last on response)
- used for common concerns (CORS, compression, tracing, timeout)
tower-http - Request-scoped data passed via extensions, not global state
- Middleware errors don't panic — they return error responses
- Edition 2024: Middleware using can migrate to native
#[async_trait]in trait implsasync fn
- Tower层按正确顺序应用(外层在请求时先执行,响应时最后执行)
- 使用处理通用需求(CORS、压缩、追踪、超时)
tower-http - 请求范围的数据通过扩展传递,而非全局状态
- 中间件错误不触发panic — 而是返回错误响应
- 2024版本:使用的中间件可以迁移到 trait 实现中的原生
#[async_trait]async fn
Severity Calibration
严重程度校准
Critical
关键
- Body extractor not last in handler parameters (silently consumes body, later extractors fail)
- SQL injection via path/query parameters passed directly to queries
- Internal error details leaked to clients (stack traces, database errors)
- Missing authentication middleware on protected routes
- 体提取器未放在处理程序参数的最后(会静默消费体,后续提取器会失败)
- 通过路径/查询参数直接传递给查询导致SQL注入
- 内部错误细节泄露给客户端(堆栈跟踪、数据库错误)
- 受保护路由缺少认证中间件
Major
主要
- Global mutable state instead of (race conditions)
State<T> - Missing error type conversion (raw returned to client)
sqlx::Error - Missing request timeout (handlers can hang indefinitely)
- Route conflicts causing unexpected 405s
- Edition 2024: still used for
async-trait/FromRequestwhen native async fn worksFromRequestParts
- 使用全局可变状态而非(存在竞态条件)
State<T> - 缺少错误类型转换(将原始返回给客户端)
sqlx::Error - 缺少请求超时(处理程序可能无限挂起)
- 路由冲突导致意外的405错误
- 2024版本:在原生async fn可用的情况下,仍为/
FromRequest使用FromRequestPartsasync-trait
Minor
次要
- Manual route method matching instead of ,
.get().post() - Missing fallback handler (default 404 is plain text, not JSON)
- Middleware applied per-route when it should be global (or vice versa)
- Missing for request logging
tower-http::trace - Edition 2024: or
once_cell::sync::Lazyused wherelazy_static!worksstd::sync::LazyLock
- 使用手动路由方法匹配而非、
.get().post() - 缺少回退处理程序(默认404是纯文本,而非JSON)
- 中间件按路由应用,而应该全局应用(反之亦然)
- 缺少用于请求日志
tower-http::trace - 2024版本:在可用的情况下,仍使用
std::sync::LazyLock或once_cell::sync::Lazylazy_static!
Informational
信息性
- Suggestions to use layers for common concerns
tower-http - Router organization improvements
- Suggestions to add OpenAPI documentation via or
utoipaaide
- 建议使用层处理通用需求
tower-http - 路由组织优化建议
- 建议通过或
utoipa添加OpenAPI文档aide
Valid Patterns (Do NOT Flag)
有效模式(无需标记)
- on handlers — Debugging aid that improves compile error messages
#[axum::debug_handler] - for middleware-injected data — Valid pattern for request-scoped values
Extension<T> - Returning from handlers — More flexible than concrete types
impl IntoResponse - per module, merged in main — Standard organization pattern
Router::new() - for layer composition — Tower pattern, not over-engineering
ServiceBuilder - with
axum::serve— Standard axum 0.7+ server setupTcpListener - Native in
async fn/FromRequestimpls —FromRequestPartscrate no longer needed (stable since Rust 1.75)async-trait - on handler return types — Edition 2024 precise capture syntax for RPIT
+ use<'a> - for shared static state — Replaces
std::sync::LazyLock/once_cell(stable since Rust 1.80)lazy_static
- 处理程序上的— 调试辅助工具,可改善编译错误信息
#[axum::debug_handler] - 使用传递中间件注入的数据 — 传递请求范围值的有效模式
Extension<T> - 处理程序返回— 比具体类型更灵活
impl IntoResponse - 每个模块使用,在主函数中合并 — 标准组织模式
Router::new() - 使用组合层 — Tower模式,不属于过度设计
ServiceBuilder - 使用配合
axum::serve— axum 0.7+的标准服务器设置TcpListener - /
FromRequest实现中的原生FromRequestParts— 不再需要async fncrate(Rust 1.75起稳定)async-trait - 处理程序返回类型中的— 2024版本中RPIT的精确捕获语法
+ use<'a> - 使用作为共享静态状态 — 替代
std::sync::LazyLock/once_cell(Rust 1.80起稳定)lazy_static
Before Submitting Findings
提交结果前
Load and follow before reporting any issue.
beagle-rust:review-verification-protocol在报告任何问题前,请加载并遵循。
beagle-rust:review-verification-protocol