allframe_core/router/
handler.rs

1//! Handler trait and implementations for protocol-agnostic request handling
2
3use std::{future::Future, pin::Pin};
4
5/// Handler trait for protocol-agnostic request handling
6///
7/// Handlers implement this trait to provide a unified interface
8/// that can be called from any protocol adapter.
9pub trait Handler: Send + Sync {
10    /// Call the handler and return a result
11    fn call(&self) -> Pin<Box<dyn Future<Output = Result<String, String>> + Send + '_>>;
12}
13
14/// Wrapper for function-based handlers with no arguments
15pub struct HandlerFn<F, Fut>
16where
17    F: Fn() -> Fut + Send + Sync,
18    Fut: Future<Output = String> + Send,
19{
20    func: F,
21}
22
23impl<F, Fut> HandlerFn<F, Fut>
24where
25    F: Fn() -> Fut + Send + Sync,
26    Fut: Future<Output = String> + Send,
27{
28    /// Create a new handler from a function
29    pub fn new(func: F) -> Self {
30        Self { func }
31    }
32}
33
34impl<F, Fut> Handler for HandlerFn<F, Fut>
35where
36    F: Fn() -> Fut + Send + Sync + 'static,
37    Fut: Future<Output = String> + Send + 'static,
38{
39    fn call(&self) -> Pin<Box<dyn Future<Output = Result<String, String>> + Send + '_>> {
40        let fut = (self.func)();
41        Box::pin(async move { Ok(fut.await) })
42    }
43}
44
45#[cfg(test)]
46mod tests {
47    use super::*;
48
49    #[tokio::test]
50    async fn test_handler_fn() {
51        let handler = HandlerFn::new(|| async { "test".to_string() });
52        let result = handler.call().await;
53        assert_eq!(result, Ok("test".to_string()));
54    }
55}