rust 在Axum 0.5中,如何在一个请求处理程序中同时使用数据库和路径解析?

wqnecbli  于 2023-11-19  发布在  其他
关注(0)|答案(1)|浏览(89)

我现在有一个工作代码:

// build our application with a route
    let app = Router::new()
        .route("/api/:start/:tokens/:left/:top/:right/:bottom", get(stats))
        .route("/dbtest", get(dbtest))
        .layer(Extension(pool))
        ;
...
// we can extract the connection pool with `Extension`
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(
    Path((start, tokens, left, top, bottom, right)): Path<(DateTime<Utc>, DashVec, u32, u32, u32, u32)>,
) -> String {
    format!("{} {:?} {:?} {:?}", start.to_rfc3339(), tokens, (left, top), (right, bottom))
}

字符串
如何创建一个既能使用数据库pool又能解析数据库Path的处理程序?

bihw5rsg

bihw5rsg1#

您可以将它们定义为单独的参数:

async fn combined(
    Extension(pool): Extension<PgPool>,
    Path((start, tokens, left, top, bottom, right)): Path<(DateTime<Utc>, DashVec, u32, u32, u32, u32)>,
) -> Result<String, (StatusCode, String)> {
    println!("{} {:?} {:?} {:?}", start.to_rfc3339(), tokens, (left, top), (right, bottom));
    sqlx::query_scalar("select 'hello world from pg'")
        .fetch_one(&pool)
        .await
        .map_err(internal_error)
}

字符串
PathExtensionextractors,处理函数可以有 “零个或多个提取器作为参数”

相关问题