Rust Warp 中的依赖注入

Dependency Injection in Rust Warp

如何将依赖项注入 Warp 中的路由处理程序?一个简单的例子如下。我有一条路线,我想提供一个在启动时确定的静态值,但过滤器是将值传递到最终处理程序的东西。如何在不创建全局变量的情况下传递附加数据?这对于依赖注入很有用。

pub fn root_route() -> BoxedFilter<()> {
    warp::get().and(warp::path::end()).boxed()
}

pub async fn root_handler(git_sha: String) -> Result<impl warp::Reply, warp::Rejection> {
    Ok(warp::reply::json(
        json!({
             "sha": git_sha
        })
            .as_object()
            .unwrap(),
    ))
}


#[tokio::main]
async fn main() {
    let git_sha = "1234567890".to_string();
    let api = root_route().and_then(root_handler);
    warp::serve(api).run(([0,0,0,0], 8080)).await;
}

这是一个简单的例子。通过将 .and().map(move ||) 结合使用 您可以将参数添加到将传递到最终处理程序函数的元组中。

use warp::filters::BoxedFilter;
use warp::Filter;
#[macro_use]
extern crate serde_json;

pub fn root_route() -> BoxedFilter<()> {
    warp::get().and(warp::path::end()).boxed()
}

pub async fn root_handler(git_sha: String) -> Result<impl warp::Reply, warp::Rejection> {
    Ok(warp::reply::json(
        json!({
             "sha": git_sha
        })
            .as_object()
            .unwrap(),
    ))
}

pub fn with_sha(git_sha: String) -> impl Filter<Extract = (String,), Error = std::convert::Infallible> + Clone {
    warp::any().map(move || git_sha.clone())
}

#[tokio::main]
async fn main() {
    let git_sha = "1234567890".to_string();
    let api = root_route().and(with_sha(git_sha)).and_then(root_handler);
    warp::serve(api).run(([0,0,0,0], 8080)).await;
}