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
use std::marker::PhantomData;
use crate::{BoxFuture, Context, Extract, Future, Middleware, Response, Result};
pub trait Handler<Args>: Clone + 'static {
type Output: Into<Response>;
type Future: Future<Output = Self::Output> + Send + 'static;
fn call(&self, args: Args) -> Self::Future;
}
#[derive(Debug, Clone)]
pub struct Endpoint<Handler, Args>(Handler, PhantomData<fn(Args)>);
impl<Handler, Args> Endpoint<Handler, Args> {
pub fn new(h: Handler) -> Self {
Self(h, PhantomData)
}
}
impl<'a, H, A> Middleware<'a, Context> for Endpoint<H, A>
where
A: Extract + Send + 'static,
A::Error: Into<Response> + Send,
H: Handler<A> + Send + Sync + 'static,
H::Output: Into<Response>,
H::Future: Future<Output = H::Output> + Send + 'static,
{
type Output = Result;
fn call(&'a self, cx: &'a mut Context) -> BoxFuture<'a, Self::Output> {
Box::pin(async move {
Ok(match A::extract(cx).await {
Ok(args) => Handler::call(&self.0, args).await.into(),
Err(e) => e.into(),
})
})
}
}