1use hyper::Body;
2use std::future::Future;
3use std::pin::Pin;
4use std::sync::Arc;
5
6pub type BoxResponseFuture = Pin<Box<dyn Future<Output = http::Response<Body>> + Send>>;
8
9#[derive(Clone)]
11pub struct HandlerFunc(Arc<dyn Fn(http::Request<Body>) -> BoxResponseFuture + Send + Sync>);
12
13impl HandlerFunc {
14 pub fn new<F, Fut>(f: F) -> Self
16 where
17 F: Fn(http::Request<Body>) -> Fut + Send + Sync + 'static,
18 Fut: Future<Output = http::Response<Body>> + Send + 'static,
19 {
20 let f = Arc::new(f);
21 Self(Arc::new(move |req| {
22 let f = f.clone();
23 Box::pin(async move { (f)(req).await })
24 }))
25 }
26
27 pub fn call(&self, req: http::Request<Body>) -> BoxResponseFuture {
29 (self.0)(req)
30 }
31}
32
33impl<F, Fut> From<F> for HandlerFunc
34where
35 F: Fn(http::Request<Body>) -> Fut + Send + Sync + 'static,
36 Fut: Future<Output = http::Response<Body>> + Send + 'static,
37{
38 fn from(f: F) -> Self {
39 HandlerFunc::new(f)
40 }
41}