allframe_core/router/
handler.rs1use std::{future::Future, pin::Pin};
4
5pub trait Handler: Send + Sync {
10 fn call(&self) -> Pin<Box<dyn Future<Output = Result<String, String>> + Send + '_>>;
12}
13
14pub 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 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}