axum/service_ext.rs
1use crate::error_handling::HandleError;
2#[cfg(feature = "tokio")]
3use crate::extract::connect_info::IntoMakeServiceWithConnectInfo;
4use crate::routing::IntoMakeService;
5use tower_service::Service;
6
7/// Extension trait that adds additional methods to any [`Service`].
8pub trait ServiceExt<R>: Service<R> + Sized {
9 /// Convert this service into a [`MakeService`], that is a [`Service`] whose
10 /// response is another service.
11 ///
12 /// This is commonly used when applying middleware around an entire [`Router`]. See ["Rewriting
13 /// request URI in middleware"] for more details.
14 ///
15 /// [`MakeService`]: tower::make::MakeService
16 /// ["Rewriting request URI in middleware"]: crate::middleware#rewriting-request-uri-in-middleware
17 /// [`Router`]: crate::Router
18 fn into_make_service(self) -> IntoMakeService<Self>;
19
20 /// Convert this service into a [`MakeService`], that will store `C`'s
21 /// associated `ConnectInfo` in a request extension such that [`ConnectInfo`]
22 /// can extract it.
23 ///
24 /// This enables extracting things like the client's remote address.
25 /// This is commonly used when applying middleware around an entire [`Router`]. See ["Rewriting
26 /// request URI in middleware"] for more details.
27 ///
28 /// [`MakeService`]: tower::make::MakeService
29 /// ["Rewriting request URI in middleware"]: crate::middleware#rewriting-request-uri-in-middleware
30 /// [`Router`]: crate::Router
31 /// [`ConnectInfo`]: crate::extract::connect_info::ConnectInfo
32 #[cfg(feature = "tokio")]
33 fn into_make_service_with_connect_info<C>(self) -> IntoMakeServiceWithConnectInfo<Self, C>;
34
35 /// Convert this service into a [`HandleError`], that will handle errors
36 /// by converting them into responses.
37 ///
38 /// See ["error handling model"] for more details.
39 ///
40 /// [`HandleError`]: crate::error_handling::HandleError
41 /// ["error handling model"]: crate::error_handling#axums-error-handling-model
42 fn handle_error<F, T>(self, f: F) -> HandleError<Self, F, T> {
43 HandleError::new(self, f)
44 }
45}
46
47impl<S, R> ServiceExt<R> for S
48where
49 S: Service<R> + Sized,
50{
51 fn into_make_service(self) -> IntoMakeService<Self> {
52 IntoMakeService::new(self)
53 }
54
55 #[cfg(feature = "tokio")]
56 fn into_make_service_with_connect_info<C>(self) -> IntoMakeServiceWithConnectInfo<Self, C> {
57 IntoMakeServiceWithConnectInfo::new(self)
58 }
59}