如何将特质作为应用程序数据传递给Actix Web?

14
我想创建一个actix-web服务器,其中我可以提供我的Search trait作为应用程序数据,以便轻松地在多个实现之间进行切换或在测试时使用模拟实现。无论我尝试什么,都不能编译它,或者当我编译它时,当在Web浏览器中访问路由时,会出现以下错误:App data is not configured, to configure use App::data()。这是我目前的情况。
# Cargo.toml
[dependencies]
actix-rt = "1.1.1"
actix-web = "3.3.2"

[dev-dependencies]
tokio = "0.2.22"
//! main.rs
use actix_web::dev::Server;
use actix_web::{get, web, App, HttpServer, Responder};

pub trait Search {
    fn search(&self, query: &str) -> String;
}

#[derive(Clone)]
pub struct SearchClient {
    base_url: String,
}

impl SearchClient {
    pub fn new() -> Self {
        Self {
            base_url: String::from("/search"),
        }
    }
}

impl Search for SearchClient {
    fn search(&self, query: &str) -> String {
        format!("Searching in SearchClient: {}", query)
    }
}

#[get("/{query}")]
async fn index(
    web::Path(query): web::Path<String>,
    search: web::Data<dyn Search>,
) -> impl Responder {
    search.into_inner().search(&query)
}

pub fn create_server(
    search: impl Search + Send + Sync + 'static + Clone,
) -> Result<Server, std::io::Error> {
    let server = HttpServer::new(move || App::new().data(search.clone()).service(index))
        .bind("127.0.0.1:8080")?
        .run();
    Ok(server)
}

#[actix_web::main]
async fn main() -> std::io::Result<()> {
    let search_client = SearchClient::new();
    create_server(search_client).unwrap().await
}

#[cfg(test)]
mod tests {
    use super::*;

    #[derive(Clone)]
    pub struct TestClient;

    impl Search for TestClient {
        fn search(&self, query: &str) -> String {
            format!("Searching in TestClient: {}", query)
        }
    }

    #[actix_rt::test]
    async fn test_search() {
        let search_client = TestClient {};
        let server = create_server(search_client).unwrap();
        tokio::spawn(server);
    }
}

你可能需要查看shaku - Ibraheem Ahmed
1个回答

13
当将data添加到您的App中时,您必须指定要将其降级为特质对象。由于Data不直接接受未调整大小的类型,因此您必须首先创建一个Arc它确实接受未调整大小的类型),然后将其转换为Data。我们将使用app_data方法来避免在双重弧中包装搜索器。
pub fn create_server(
    search: impl Search + Send + Sync + 'static,
) -> Result<Server, std::io::Error> {
    let search: Data<dyn Search> = Data::from(Arc::new(search));
    
    HttpServer::new(move || {
        App::new()
            .app_data(search.clone())
    })
}

async fn index(
    query: Path<String>,
    search: Data<dyn Search>,
) -> impl Responder {     
    search.into_inner().search(&*query)
}

另一种方法是使用泛型。您的处理程序和create_server函数将基于Search实现进行泛化:

async fn index<T: Search>(
    web::Path(query): web::Path<String>,
    search: web::Data<T>,
-> impl Responder {
    search.into_inner().search(&query)
}

pub fn create_server<T: Search + Send + Sync + 'static + Clone>(
    search: T,
) -> Result<Server, std::io::Error> {
    let server = HttpServer::new(move || {
        App::new()
            .data(search.clone())
            .route("/{query}", web::get().to(index::<T>))
    })
    .bind("127.0.0.1:8080")?
    .run();
    Ok(server)
}

现在,在 main 中创建服务器时,您可以使用 SearchClient

#[actix_web::main]
async fn main() -> std::io::Result<()> {
     let search_client = SearchClient::new();
     create_server(search_client).unwrap().await
}

当你为测试目的创建服务器时,可以使用一个TestClient

#[actix_rt::test]
async fn test_search() {
    let search_client = TestClient {};
    let server = create_server(search_client).unwrap();
}

使用泛型方法的劣势在于您无法使用 #[get("")] 宏路由,因为您必须指定处理程序的泛型参数。
App::new()
    .route("/{query}", web::get().to(index::<T>))

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接