这是我的代码。我正在尝试从Rust subreddit获得帖子。我将使用Actix的内置客户端,但在Windows上无法使用,因此改用reqwest
:
use actix_web::{self, middleware, web, App, HttpRequest, HttpServer};
use futures::future::Future;
use reqwest::{
self,
r#async::{Client},
};
fn get_rust_posts(
_req: HttpRequest,
client: web::Data<Client>,
) -> impl Future<Item = String, Error = reqwest::Error> {
client
.get("http://www.reddit.com/r/rust.json")
.send()
.and_then(|mut resp| resp.text())
.map_err(|err| {
println!("Error in get rust posts: {}", err);
err
})
}
fn main() {
let mut server = HttpServer::new(|| {
App::new()
.data(Client::new())
.wrap(middleware::Logger::default())
.service(web::resource("/get/rust/posts").route(web::get().to_async(get_rust_posts)))
});
server.bind(("0.0.0.0", 8000)).unwrap().run().unwrap();
}
[dependencies]
actix-web = "1.0.8"
futures = "0.1.29"
reqwest = "0.9.21"
这是错误:
error[E0277]: the trait bound `fn(actix_web::request::HttpRequest, actix_web::data::Data<reqwest::async_impl::client::Client>) -> impl futures::future::Future
{get_rust_posts}: actix_web::handler::AsyncFactory<_, _>` is not satisfied
--> src\main.rs:29:72
|
29 | .service(web::resource("/get/rust/posts").route(web::get().to_async(get_rust_posts)))
| ^^^^^^^^ the trait `actix_web::handler::AsyncFactory<_, _>` is not implemented for
`fn(actix_web::request::HttpRequest, actix_web::data::Data<reqwest::async_impl::client::Client>) -> impl futures::future::Future {get_rust_posts}
答案 0 :(得分:0)
to_async需要一个处理程序功能,该功能实现特征AsyncFactory
。将Future
的{{1}}更改为Item
并将actix_web::HttpResponse
请求放入reqwest
中即可满足该约束。
我还以较慢的响应速度对此进行了测试,尽管actix_web::web::block
中有“ block”一词,它似乎可以处理并发请求,我认为这是因为处理程序本身是异步的。
actix_web::web::block