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

Rust 如何将特性作为应用程序数据传递给Actix Web?,rust,traits,actix-web,Rust,Traits,Actix Web,我想创建一个服务器,在那里我可以提供我的搜索特性作为应用程序数据,以便在多个实现之间轻松交换,或者使用模拟实现进行测试。无论我尝试什么,我都无法将其编译,或者当我将其编译时,在web浏览器中访问路由时会出现以下错误: 未配置应用程序数据,若要配置,请使用App::data() 这是我到目前为止所拥有的 //main.rs 使用actix_web::dev::Server; 使用actix_web::{get,web,App,HttpServer,Responder}; 发布特征搜索{ fn搜索(

我想创建一个服务器,在那里我可以提供我的
搜索
特性作为应用程序数据,以便在多个实现之间轻松交换,或者使用模拟实现进行测试。无论我尝试什么,我都无法将其编译,或者当我将其编译时,在web浏览器中访问路由时会出现以下错误:

未配置应用程序数据,若要配置,请使用App::data()

这是我到目前为止所拥有的

//main.rs
使用actix_web::dev::Server;
使用actix_web::{get,web,App,HttpServer,Responder};
发布特征搜索{
fn搜索(&self,查询:&str)->字符串;
}
#[衍生(克隆)]
发布结构搜索客户端{
基本url:String,
}
impl搜索客户端{
pub fn new()->Self{
自我{
基本url:String::from(“/search”),
}
}
}
搜索搜索客户端的impl搜索{
fn搜索(&self,查询:&str)->字符串{
格式!(“在SearchClient:{}中搜索”,查询)
}
}
#[获取(“/{query}”)]
异步fn索引(
web::Path(查询):web::Path,
搜索:web::Data,
)->impl应答器{
search.into_inner().search(&query)
}
发布fn创建_服务器(
搜索:简单搜索+发送+同步+静态+克隆,
)->结果{
让server=HttpServer::new(move | | App::new().data(search.clone()).service(index))
.bind(“127.0.0.1:8080”)?
.run();
Ok(服务器)
}
#[actix_web::main]
异步fn main()->std::io::Result{
让search_client=SearchClient::new();
创建服务器(搜索客户端)。展开()。等待
}
#[cfg(测试)]
模试验{
使用超级::*;
#[衍生(克隆)]
pub-struct-TestClient;
对TestClient的impl搜索{
fn搜索(&self,查询:&str)->字符串{
格式!(“在TestClient:{}中搜索”,查询)
}
}
#[活动:测试]
异步fn测试_搜索(){
让search_client=TestClient{};
let server=create_server(search_client).unwrap();
tokio::spawn(服务器);
}
}

数据
添加到
应用程序
时,必须指定要将其降级为特征对象<代码>数据不直接接受未调整大小的类型,因此您必须首先创建一个
(),然后将其转换为
数据
。我们将使用
app_data
方法来避免将搜索者包装成双圆弧

pub fn创建\u服务器(
搜索:简单搜索+发送+同步+静态,
)->结果{
让搜索:Data=Data::from(Arc::new(search));
HttpServer::新建(移动| |{
App::new()
.app_数据(search.clone())
})
}
异步fn索引(
查询:路径,
搜索:数据,
)->impl响应程序{
search.into_inner().search(&*query)
}
另一种方法是使用泛型。您的处理程序和
create\u服务器
函数在
搜索
实现上是通用的:

异步fn索引(
web::Path(查询):web::Path,
搜索:web::Data,
->impl应答器{
search.into_inner().search(&query)
}
pub fn创建您可能想要查看的服务器
# Cargo.toml

[package]
name = "actix-trait"
version = "0.1.0"
edition = "2018"

[dependencies]
actix-rt = "1.1.1"
actix-web = "3.3.2"

[dev-dependencies]
tokio = "0.2.22"