使用这个最小的异步 actix-web 服务器
use actix_web::{http, server, App, HttpRequest, HttpResponse, Error}; // v. 0.7.19
use futures::Future; // v. 0.1.28
/// An Asynchronous response which will either "fail fast" on the outer `Result` or
/// return a future which may itself succeed or fail
/// The lifetime parameter is required to indicate that the future cannot outlive
/// the parameter - the `req: &HttpRequest` - of the handler (`handle_request`)
type AsyncCResponse<'a> =
Result<Box<Future<Item = HttpResponse, Error = Error> + 'a>, Error>;
/// lifetimes have been elided but here the future in the `AsyncCResponse`
/// will have the same lifetime as the `req` HttpRequest
fn handle_request(req: &HttpRequest<()>) -> AsyncCResponse {
// handle the request
Ok(Box::new(futures::future::ok(HttpResponse::Ok().body("Hello World"))))
}
fn main() {
// instantiation of an actix-web server
server::new(move || {
App::new()
.resource("/", |r| {
r.method(http::Method::GET).f(|r: &HttpRequest<()>| handle_request(r))
})
});
}
编译失败
error[E0495]: cannot infer an appropriate lifetime for lifetime parameter in function call due to conflicting requirements
--> src/main.rs:23:69
|
23 | r.method(http::Method::GET).f(|r: &HttpRequest<()>| handle_request(r))
| ^^^^^^^^^^^^^^^^^
|
note: first, the lifetime cannot outlive the anonymous lifetime #2 defined on the body at 23:47...
--> src/main.rs:23:47
|
23 | r.method(http::Method::GET).f(|r: &HttpRequest<()>| handle_request(r))
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
note: ...so that reference does not outlive borrowed content
--> src/main.rs:23:84
|
23 | r.method(http::Method::GET).f(|r: &HttpRequest<()>| handle_request(r))
| ^
= note: but, the lifetime must be valid for the static lifetime...
= note: ...so that the types are compatible:
expected actix_web::handler::Responder
found actix_web::handler::Responder
f
在 actix-web 中的定义是
/// Set handler function. Usually call to this method is last call
/// during route configuration, so it does not return reference to self.
pub fn f<F, R>(&mut self, handler: F)
where
F: Fn(&HttpRequest<S>) -> R + 'static,
R: Responder + 'static,
{
self.handler = InnerHandler::new(handler);
}
我是否正确理解编译失败是因为
- 的定义
f
要求处理程序F
返回具有'static
生命周期的响应 - 当给定处理程序返回的响应
handle_request
具有绑定到HttpRequest
参数的生命周期时?
我有什么办法可以在不改变定义的情况下解决这个问题AsyncCResponse
?