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 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317
use std::future::Future;
use crate::middleware::Middleware;
use crate::util::assert_service;
use super::{
AndThen, ArcService, BoxCloneService, BoxService, MapErr, MapRequest, MapResponse, MapResult,
OrElse, Service, Then,
};
/// [`Service`]的扩展特征,提供了一些方便的功能。
pub trait ServiceExt<Req>: Service<Req> {
/// 在此服务上应用中间件。
///
/// # 例子
///
/// ```
/// use boluo_core::handler::handler_fn;
/// use boluo_core::middleware::middleware_fn;
/// use boluo_core::request::Request;
/// use boluo_core::service::{Service, ServiceExt};
///
/// fn add_extension<S>(service: S) -> impl Service<Request>
/// where
/// S: Service<Request>,
/// {
/// service.map_request(|mut req: Request| {
/// req.extensions_mut().insert("My Extension");
/// req
/// })
/// }
///
/// let service = handler_fn(|| async {});
/// let service = service.with(middleware_fn(add_extension));
/// ```
fn with<T>(self, middleware: T) -> T::Service
where
Self: Sized,
T: Middleware<Self>,
{
middleware.transform(self)
}
/// 在此服务执行完成后执行给定的异步函数。
///
/// # 例子
///
/// ```
/// use boluo_core::service::{service_fn, ServiceExt};
///
/// #[derive(Debug)]
/// struct MyError;
///
/// impl std::fmt::Display for MyError {
/// fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
/// write!(f, "some error message")
/// }
/// }
///
/// impl std::error::Error for MyError {}
///
/// async fn throw_error(_: ()) -> Result<(), MyError> {
/// Err(MyError)
/// }
///
/// let service = service_fn(throw_error);
/// let service = service.then(|result| async move {
/// if let Err(err) = &result {
/// // 打印错误信息。
/// println!("{err}");
/// }
/// result
/// });
/// ```
fn then<F, Fut, Res, Err>(self, f: F) -> Then<Self, F>
where
Self: Sized,
F: Fn(Result<Self::Response, Self::Error>) -> Fut + Send + Sync,
Fut: Future<Output = Result<Res, Err>> + Send,
{
assert_service(Then::new(self, f))
}
/// 在此服务执行成功后执行给定的异步函数。
///
/// # 例子
///
/// ```
/// use boluo_core::body::Body;
/// use boluo_core::handler::handler_fn;
/// use boluo_core::service::ServiceExt;
/// use boluo_core::BoxError;
///
/// async fn hello() -> &'static str {
/// "Hello, World!"
/// }
///
/// let service = handler_fn(hello);
/// let service = service.and_then(|response| async move {
/// // 清空响应主体。
/// Ok::<_, BoxError>(response.map(|_| Body::empty()))
/// });
/// ```
fn and_then<F, Fut, Res>(self, f: F) -> AndThen<Self, F>
where
Self: Sized,
F: Fn(Self::Response) -> Fut + Send + Sync,
Fut: Future<Output = Result<Res, Self::Error>> + Send,
{
assert_service(AndThen::new(self, f))
}
/// 在此服务执行失败后执行给定的异步函数。
///
/// # 例子
///
/// ```
/// use boluo_core::handler::handler_fn;
/// use boluo_core::http::StatusCode;
/// use boluo_core::response::IntoResponse;
/// use boluo_core::service::ServiceExt;
///
/// #[derive(Debug)]
/// struct MyError;
///
/// impl std::fmt::Display for MyError {
/// fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
/// write!(f, "some error message")
/// }
/// }
///
/// impl std::error::Error for MyError {}
///
/// async fn throw_error() -> Result<(), MyError> {
/// Err(MyError)
/// }
///
/// let service = handler_fn(throw_error);
/// let service = service.or_else(|err| async move {
/// // 捕获错误并转换为响应。
/// if let Some(e) = err.downcast_ref::<MyError>() {
/// let status = StatusCode::INTERNAL_SERVER_ERROR;
/// return Ok((status, format!("{e}")).into_response()?);
/// }
/// Err(err)
/// });
/// ```
fn or_else<F, Fut, Err>(self, f: F) -> OrElse<Self, F>
where
Self: Sized,
F: Fn(Self::Error) -> Fut + Send + Sync,
Fut: Future<Output = Result<Self::Response, Err>> + Send,
{
assert_service(OrElse::new(self, f))
}
/// 将此服务返回的结果映射为其他值。
///
/// # 例子
///
/// ```
/// use std::convert::Infallible;
///
/// use boluo_core::response::{IntoResponse, Response};
/// use boluo_core::service::{service_fn, ServiceExt};
///
/// #[derive(Debug)]
/// struct MyError;
///
/// impl std::fmt::Display for MyError {
/// fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
/// write!(f, "some error message")
/// }
/// }
///
/// impl std::error::Error for MyError {}
///
/// async fn throw_error(_: ()) -> Result<(), MyError> {
/// Err(MyError)
/// }
///
/// let service = service_fn(throw_error);
/// let service = service.map_result(|result| -> Result<Response, Infallible> {
/// match result {
/// Ok(r) => r.into_response(),
/// Err(e) => format!("{e}").into_response(),
/// }
/// });
/// ```
fn map_result<F, Res, Err>(self, f: F) -> MapResult<Self, F>
where
Self: Sized,
F: Fn(Result<Self::Response, Self::Error>) -> Result<Res, Err> + Send + Sync,
{
assert_service(MapResult::new(self, f))
}
/// 将此服务返回的响应映射为其他值。
///
/// # 例子
///
/// ```
/// use std::convert::Infallible;
///
/// use boluo_core::body::Body;
/// use boluo_core::service::{service_fn, ServiceExt};
///
/// async fn hello(_: ()) -> Result<&'static str, Infallible> {
/// Ok("Hello, World!")
/// }
///
/// let service = service_fn(hello);
/// let service = service.map_response(|text| Body::from(text));
/// ```
fn map_response<F, Res>(self, f: F) -> MapResponse<Self, F>
where
Self: Sized,
F: Fn(Self::Response) -> Res + Send + Sync,
{
assert_service(MapResponse::new(self, f))
}
/// 将此服务返回的错误映射为其他值。
///
/// # 例子
///
/// ```
/// use boluo_core::service::{service_fn, ServiceExt};
/// use boluo_core::BoxError;
///
/// #[derive(Debug)]
/// struct MyError;
///
/// impl std::fmt::Display for MyError {
/// fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
/// write!(f, "some error message")
/// }
/// }
///
/// impl std::error::Error for MyError {}
///
/// async fn throw_error(_: ()) -> Result<(), MyError> {
/// Err(MyError)
/// }
///
/// let service = service_fn(throw_error);
/// let service = service.map_err(|err| BoxError::from(err));
/// ```
fn map_err<F, Err>(self, f: F) -> MapErr<Self, F>
where
Self: Sized,
F: Fn(Self::Error) -> Err + Send + Sync,
{
assert_service(MapErr::new(self, f))
}
/// 将发送给此服务的请求映射为其他值。
///
/// # 例子
///
/// ```
/// use std::convert::Infallible;
///
/// use boluo_core::service::{service_fn, Service, ServiceExt};
///
/// async fn echo(text: String) -> Result<String, Infallible> {
/// Ok(text)
/// }
///
/// let service = service_fn(echo);
/// let service = service.map_request(|slice: &[u8]| {
/// // 将字节片转换为包含无效字符的字符串。
/// String::from_utf8_lossy(slice).into_owned()
/// });
///
/// let fut = service.call(b"Hello, World");
/// ```
fn map_request<F, R>(self, f: F) -> MapRequest<Self, F>
where
Self: Sized,
F: Fn(R) -> Req + Send + Sync,
{
assert_service(MapRequest::new(self, f))
}
/// 将此服务转换为[`Service`]特征对象并装箱。
///
/// 更多详细信息,请参阅[`BoxService`]。
fn boxed(self) -> BoxService<Req, Self::Response, Self::Error>
where
Self: Sized + 'static,
{
assert_service(BoxService::new(self))
}
/// 将此服务转换为[`Service`]特征对象并装箱。
///
/// 更多详细信息,请参阅[`BoxCloneService`]。
fn boxed_clone(self) -> BoxCloneService<Req, Self::Response, Self::Error>
where
Self: Sized + Clone + 'static,
{
assert_service(BoxCloneService::new(self))
}
/// 将此服务转换为[`Service`]特征对象并装箱。
///
/// 更多详细信息,请参阅[`ArcService`]。
fn boxed_arc(self) -> ArcService<Req, Self::Response, Self::Error>
where
Self: Sized + 'static,
{
assert_service(ArcService::new(self))
}
}
impl<S: ?Sized, Req> ServiceExt<Req> for S where S: Service<Req> {}