You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Axum 0.5:如何在单个请求处理器中同时使用数据库与路径解析

如何编写同时支持数据库连接池与路径参数解析的请求处理器

你只需要把Path路径参数提取器和Extension<PgPool>数据库连接池提取器同时作为请求处理器的参数即可,Axum支持在同一个函数中使用多个提取器,会自动根据参数类型完成对应的数据提取。

修改后的完整示例代码

// 构建应用路由(原路由无需修改,已注入Extension层)
let app = Router::new()
    .route("/api/:start/:tokens/:left/:top/:right/:bottom", get(stats_with_db))
    .route("/dbtest", get(dbtest))
    .layer(Extension(pool));

// 原有的dbtest处理器
async fn dbtest(
    Extension(pool): Extension<PgPool>,
) -> Result<String, (StatusCode, String)> {
    sqlx::query_scalar("select 'hello world from pg'")
        .fetch_one(&pool)
        .await
        .map_err(internal_error)
}

// 同时支持路径参数和数据库连接池的新处理器
async fn stats_with_db(
    Path((start, tokens, left, top, bottom, right)): Path<(DateTime<Utc>, DashVec, u32, u32, u32, u32)>,
    Extension(pool): Extension<PgPool>,
) -> Result<String, (StatusCode, String)> {
    // 使用路径参数做业务逻辑处理
    let param_info = format!("{} {:?} {:?} {:?}", start.to_rfc3339(), tokens, (left, top), (right, bottom));
    println!("Received request params: {}", param_info);

    // 使用数据库连接池执行查询
    let db_response = sqlx::query_scalar("select concat('Hello from DB for params: ', $1)")
        .bind(param_info)
        .fetch_one(&pool)
        .await
        .map_err(internal_error)?;

    // 返回结合路径参数与数据库结果的响应
    Ok(db_response)
}

关键说明

  • 参数声明顺序不影响Axum的提取逻辑,只要类型匹配即可
  • 错误处理可以和原dbtest函数保持一致,用map_err(internal_error)统一转换数据库操作的错误
  • 你可以在函数内自由组合路径参数的使用和数据库操作,完成任意业务逻辑

内容的提问来源于stack exchange,提问作者fadedbee

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.07 10:57:37