1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
use crate::protocol::body::ReqBody;
use http::{Request, Response};
use http_body::Body;
use std::error::Error;
use std::future::Future;

pub trait Handler: Send + Sync {
    type RespBody: Body;
    type Error: Into<Box<dyn Error + Send + Sync>>;
    type Fut<'fut>: Future<Output = Result<Response<Self::RespBody>, Self::Error>>
    where
        Self: 'fut;

    fn call(&self, req: Request<ReqBody>) -> Self::Fut<'_>;
}

#[derive(Debug)]
pub struct HandlerFn<F> {
    f: F,
}

impl<RespBody, Err, F, Fut> Handler for HandlerFn<F>
where
    RespBody: Body,
    F: Fn(Request<ReqBody>) -> Fut + Send + Sync,
    Err: Into<Box<dyn Error + Send + Sync>>,
    Fut: Future<Output = Result<Response<RespBody>, Err>> + Send,
{
    type RespBody = RespBody;
    type Error = Err;
    type Fut<'fut> = Fut where Self: 'fut;

    fn call(&self, req: Request<ReqBody>) -> Self::Fut<'_> {
        (self.f)(req)
    }
}

pub fn make_handler<F, RespBody, Err, Ret>(f: F) -> HandlerFn<F>
where
    RespBody: Body,
    Err: Into<Box<dyn Error + Send + Sync>>,
    Ret: Future<Output = Result<Response<RespBody>, Err>>,
    F: Fn(Request<ReqBody>) -> Ret,
{
    HandlerFn { f }
}