1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
//! 中间件的特征和相关类型的定义。
pub use *;
pub use *;
/// 用于表示中间件的特征。
///
/// # 例子
///
/// ```
/// use boluo_core::handler::handler_fn;
/// use boluo_core::middleware::Middleware;
/// use boluo_core::request::Request;
/// use boluo_core::response::{IntoResponse, Response};
/// use boluo_core::service::{Service, ServiceExt};
/// use boluo_core::BoxError;
///
/// /// 记录请求日志的中间件。
/// #[derive(Debug, Clone, Copy)]
/// struct Log;
///
/// /// 为日志中间件实现 [`Middleware`] 特征。
/// impl<S> Middleware<S> for Log
/// where
/// S: Service<Request>,
/// S::Response: IntoResponse,
/// S::Error: Into<BoxError>,
/// {
/// type Service = LogService<S>;
///
/// fn transform(self, service: S) -> Self::Service {
/// LogService { service }
/// }
/// }
///
/// /// 日志中间件生成的新服务。
/// #[derive(Debug, Clone, Copy)]
/// struct LogService<S> {
/// service: S,
/// }
///
/// impl<S> Service<Request> for LogService<S>
/// where
/// S: Service<Request>,
/// S::Response: IntoResponse,
/// S::Error: Into<BoxError>,
/// {
/// type Response = Response;
/// type Error = BoxError;
///
/// async fn call(&self, req: Request) -> Result<Self::Response, Self::Error> {
/// println!("req -> {} {}", req.method(), req.uri().path());
///
/// let result = self
/// .service
/// .call(req)
/// .await
/// .map_err(Into::into)
/// .and_then(|r| r.into_response().map_err(Into::into));
///
/// match &result {
/// Ok(response) => {
/// println!("res -> {}", response.status());
/// }
/// Err(err) => {
/// println!("err -> {err}");
/// }
/// }
///
/// result
/// }
/// }
///
/// async fn hello() -> &'static str {
/// "Hello, World!"
/// }
///
/// let service = handler_fn(hello);
/// let service = service.with(Log); // 添加日志中间件。
/// ```