Skip to main content

ullun/
handler.rs

1//! Handler traits and types
2
3use 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
11/// Boxed future for handlers
12pub type BoxFuture<'a, T> = Pin<Box<dyn Future<Output = T> + Send + 'a>>;
13
14/// Handler trait for route handlers
15#[async_trait]
16pub trait Handler: Send + Sync + 'static {
17    async fn call(&self, req: Request) -> Result<Response>;
18}
19
20/// Implement Handler for async functions
21#[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
32/// Handler wrapper with params
33pub 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
54/// Type-erased handler
55pub type DynHandler = Arc<dyn Handler>;