boluo_core/service/
service_fn.rs

1use super::Service;
2
3/// 将给定的异步函数转换为[`Service`]。
4///
5/// # 例子
6///
7/// ```
8/// use std::convert::Infallible;
9///
10/// use boluo_core::service::service_fn;
11///
12/// async fn hello(_: ()) -> Result<&'static str, Infallible> {
13///     Ok("Hello, World!")
14/// }
15///
16/// let service = service_fn(hello);
17/// ```
18pub fn service_fn<F>(f: F) -> ServiceFn<F> {
19    ServiceFn { f }
20}
21
22/// 将给定的异步函数转换为[`Service`]。
23#[derive(Clone, Copy)]
24
25pub struct ServiceFn<F> {
26    f: F,
27}
28
29impl<F, Fut, Req, Res, Err> Service<Req> for ServiceFn<F>
30where
31    F: Fn(Req) -> Fut + Send + Sync,
32    Fut: Future<Output = Result<Res, Err>> + Send,
33{
34    type Response = Res;
35    type Error = Err;
36
37    fn call(&self, req: Req) -> impl Future<Output = Result<Self::Response, Self::Error>> + Send {
38        (self.f)(req)
39    }
40}
41
42impl<F> std::fmt::Debug for ServiceFn<F> {
43    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
44        f.debug_struct("ServiceFn")
45            .field("f", &std::any::type_name::<F>())
46            .finish()
47    }
48}