boluo_core/service/
mod.rs

1//! 服务的特征和相关类型的定义。
2
3mod and_then;
4pub use and_then::AndThen;
5
6mod boxed;
7pub use boxed::{ArcService, BoxCloneService, BoxService};
8
9mod ext;
10pub use ext::ServiceExt;
11
12mod map_err;
13pub use map_err::MapErr;
14
15mod map_request;
16pub use map_request::MapRequest;
17
18mod map_response;
19pub use map_response::MapResponse;
20
21mod map_result;
22pub use map_result::MapResult;
23
24mod or_else;
25pub use or_else::OrElse;
26
27mod service_fn;
28pub use service_fn::{ServiceFn, service_fn};
29
30mod then;
31pub use then::Then;
32
33use std::sync::Arc;
34
35/// 表示一个接收请求并返回响应的异步函数。
36///
37/// # 例子
38///
39/// ```
40/// use std::convert::Infallible;
41///
42/// use boluo_core::request::Request;
43/// use boluo_core::response::Response;
44/// use boluo_core::service::Service;
45///
46/// // 回声服务,响应请求主体。
47/// struct Echo;
48///
49/// impl Service<Request> for Echo {
50///     type Response = Response;
51///     type Error = Infallible;
52///
53///     async fn call(&self, req: Request) -> Result<Self::Response, Self::Error> {
54///         Ok(Response::new(req.into_body()))
55///     }
56/// }
57/// ```
58pub trait Service<Req>: Send + Sync {
59    /// 服务返回的响应。
60    type Response;
61
62    /// 服务产生的错误。
63    type Error;
64
65    /// 处理请求并异步返回响应。
66    fn call(&self, req: Req) -> impl Future<Output = Result<Self::Response, Self::Error>> + Send;
67}
68
69impl<S, Req> Service<Req> for &mut S
70where
71    S: Service<Req> + ?Sized,
72{
73    type Response = S::Response;
74    type Error = S::Error;
75
76    fn call(&self, req: Req) -> impl Future<Output = Result<Self::Response, Self::Error>> + Send {
77        S::call(self, req)
78    }
79}
80
81impl<S, Req> Service<Req> for &S
82where
83    S: Service<Req> + ?Sized,
84{
85    type Response = S::Response;
86    type Error = S::Error;
87
88    fn call(&self, req: Req) -> impl Future<Output = Result<Self::Response, Self::Error>> + Send {
89        S::call(self, req)
90    }
91}
92
93impl<S, Req> Service<Req> for Box<S>
94where
95    S: Service<Req> + ?Sized,
96{
97    type Response = S::Response;
98    type Error = S::Error;
99
100    fn call(&self, req: Req) -> impl Future<Output = Result<Self::Response, Self::Error>> + Send {
101        S::call(self, req)
102    }
103}
104
105impl<S, Req> Service<Req> for Arc<S>
106where
107    S: Service<Req> + ?Sized,
108{
109    type Response = S::Response;
110    type Error = S::Error;
111
112    fn call(&self, req: Req) -> impl Future<Output = Result<Self::Response, Self::Error>> + Send {
113        S::call(self, req)
114    }
115}