actix_web_async_compat/lib.rs
1//! Actix web 1.x async/await shim.
2
3use futures::{self, compat::Compat, FutureExt, TryFutureExt};
4use std::pin::Pin;
5
6/// Convert a async fn into a actix-web handler.
7///
8/// ```rust
9/// use actix_web::{web, App, HttpResponse, Error};
10/// use std::time::{Instant, Duration};
11/// use tokio::timer::Delay;
12/// use actix_web_async_compat::async_compat;
13///
14/// async fn index() -> Result<HttpResponse, Error> {
15/// // wait 2s
16/// Delay::new(Instant::now() + Duration::from_secs(2)).await?;
17/// ok(HttpResponse::Ok().finish())
18/// }
19///
20/// App::new().service(web::resource("/").route(
21/// web::to_async(async_compat(index)))
22/// );
23/// ```
24pub fn async_compat<F, P, R, O, E>(
25 f: F,
26) -> impl Fn(P) -> Compat<Pin<Box<dyn futures::Future<Output = Result<O, E>>>>> + Clone
27where
28 F: Fn(P) -> R + Clone + 'static,
29 P: 'static,
30 R: futures::Future<Output = Result<O, E>> + 'static,
31 O: 'static,
32 E: 'static,
33{
34 move |u| f(u).boxed_local().compat()
35}