1use crate::error::Result;
4use crate::request::{Params, Request};
5use crate::response::Response;
6use async_trait::async_trait;
7use std::future::Future;
8use std::pin::Pin;
9use std::sync::Arc;
10
11pub type BoxFuture<'a, T> = Pin<Box<dyn Future<Output = T> + Send + 'a>>;
13
14#[async_trait]
16pub trait Handler: Send + Sync + 'static {
17 async fn call(&self, req: Request) -> Result<Response>;
18}
19
20#[async_trait]
22impl<F, Fut> Handler for F
23where
24 F: Fn(Request) -> Fut + Send + Sync + 'static,
25 Fut: Future<Output = Result<Response>> + Send + 'static,
26{
27 async fn call(&self, req: Request) -> Result<Response> {
28 (self)(req).await
29 }
30}
31
32pub struct HandlerWithParams<F> {
34 handler: F,
35}
36
37impl<F> HandlerWithParams<F> {
38 pub fn new(handler: F) -> Self {
39 Self { handler }
40 }
41}
42
43#[async_trait]
44impl<F, Fut> Handler for HandlerWithParams<F>
45where
46 F: Fn(Params) -> Fut + Send + Sync + 'static,
47 Fut: Future<Output = Result<Response>> + Send + 'static,
48{
49 async fn call(&self, req: Request) -> Result<Response> {
50 (self.handler)(req.params).await
51 }
52}
53
54pub type DynHandler = Arc<dyn Handler>;