Skip to main content

axum/handler/
service.rs

1use super::Handler;
2use crate::body::{Body, Bytes, HttpBody};
3#[cfg(feature = "tokio")]
4use crate::extract::connect_info::IntoMakeServiceWithConnectInfo;
5use crate::response::Response;
6use crate::routing::IntoMakeService;
7use crate::BoxError;
8use http::Request;
9use std::{
10    convert::Infallible,
11    fmt,
12    marker::PhantomData,
13    task::{Context, Poll},
14};
15use tower_service::Service;
16
17/// An adapter that makes a [`Handler`] into a [`Service`].
18///
19/// Created with [`Handler::with_state`] or [`HandlerWithoutStateExt::into_service`].
20///
21/// [`HandlerWithoutStateExt::into_service`]: super::HandlerWithoutStateExt::into_service
22pub struct HandlerService<H, T, S> {
23    handler: H,
24    state: S,
25    _marker: PhantomData<fn() -> T>,
26}
27
28impl<H, T, S> HandlerService<H, T, S> {
29    /// Get a reference to the state.
30    pub fn state(&self) -> &S {
31        &self.state
32    }
33
34    /// Convert the handler into a [`MakeService`].
35    ///
36    /// This allows you to serve a single handler if you don't need any routing:
37    ///
38    /// ```rust
39    /// use axum::{
40    ///     handler::Handler,
41    ///     extract::State,
42    ///     http::{Uri, Method},
43    ///     response::IntoResponse,
44    /// };
45    /// use std::net::SocketAddr;
46    ///
47    /// #[derive(Clone)]
48    /// struct AppState {}
49    ///
50    /// async fn handler(State(state): State<AppState>) {
51    ///     // ...
52    /// }
53    ///
54    /// let app = handler.with_state(AppState {});
55    ///
56    /// # async {
57    /// let listener = tokio::net::TcpListener::bind("0.0.0.0:3000").await.unwrap();
58    /// axum::serve(listener, app.into_make_service()).await;
59    /// # };
60    /// ```
61    ///
62    /// [`MakeService`]: tower::make::MakeService
63    pub fn into_make_service(self) -> IntoMakeService<Self> {
64        IntoMakeService::new(self)
65    }
66
67    /// Convert the handler into a [`MakeService`] which stores information
68    /// about the incoming connection.
69    ///
70    /// See [`Router::into_make_service_with_connect_info`] for more details.
71    ///
72    /// ```rust
73    /// use axum::{
74    ///     handler::Handler,
75    ///     response::IntoResponse,
76    ///     extract::{ConnectInfo, State},
77    /// };
78    /// use std::net::SocketAddr;
79    ///
80    /// #[derive(Clone)]
81    /// struct AppState {};
82    ///
83    /// async fn handler(
84    ///     ConnectInfo(addr): ConnectInfo<SocketAddr>,
85    ///     State(state): State<AppState>,
86    /// ) -> String {
87    ///     format!("Hello {addr}")
88    /// }
89    ///
90    /// let app = handler.with_state(AppState {});
91    ///
92    /// # async {
93    /// let listener = tokio::net::TcpListener::bind("0.0.0.0:3000").await.unwrap();
94    /// axum::serve(
95    ///     listener,
96    ///     app.into_make_service_with_connect_info::<SocketAddr>(),
97    /// ).await;
98    /// # };
99    /// ```
100    ///
101    /// [`MakeService`]: tower::make::MakeService
102    /// [`Router::into_make_service_with_connect_info`]: crate::routing::Router::into_make_service_with_connect_info
103    #[cfg(feature = "tokio")]
104    pub fn into_make_service_with_connect_info<C>(self) -> IntoMakeServiceWithConnectInfo<Self, C> {
105        IntoMakeServiceWithConnectInfo::new(self)
106    }
107}
108
109#[test]
110fn traits() {
111    use crate::test_helpers::*;
112    assert_send::<HandlerService<(), NotSendSync, ()>>();
113    assert_sync::<HandlerService<(), NotSendSync, ()>>();
114}
115
116impl<H, T, S> HandlerService<H, T, S> {
117    pub(super) fn new(handler: H, state: S) -> Self {
118        Self {
119            handler,
120            state,
121            _marker: PhantomData,
122        }
123    }
124}
125
126impl<H, T, S> fmt::Debug for HandlerService<H, T, S> {
127    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
128        f.debug_struct("IntoService").finish_non_exhaustive()
129    }
130}
131
132impl<H, T, S> Clone for HandlerService<H, T, S>
133where
134    H: Clone,
135    S: Clone,
136{
137    fn clone(&self) -> Self {
138        Self {
139            handler: self.handler.clone(),
140            state: self.state.clone(),
141            _marker: PhantomData,
142        }
143    }
144}
145
146impl<H, T, S, B> Service<Request<B>> for HandlerService<H, T, S>
147where
148    H: Handler<T, S> + Clone + Send + 'static,
149    B: HttpBody<Data = Bytes> + Send + 'static,
150    B::Error: Into<BoxError>,
151    S: Clone + Send + Sync,
152{
153    type Response = Response;
154    type Error = Infallible;
155    type Future = super::future::IntoServiceFuture<H::Future>;
156
157    #[inline]
158    fn poll_ready(&mut self, _cx: &mut Context<'_>) -> Poll<Result<(), Self::Error>> {
159        // `IntoService` can only be constructed from async functions which are always ready, or
160        // from `Layered` which buffers in `<Layered as Handler>::call` and is therefore
161        // also always ready.
162        Poll::Ready(Ok(()))
163    }
164
165    fn call(&mut self, req: Request<B>) -> Self::Future {
166        use futures_util::future::FutureExt;
167
168        let req = req.map(Body::new);
169
170        let handler = self.handler.clone();
171        let future = Handler::call(handler, req, self.state.clone());
172        let future = future.map(Ok as _);
173
174        super::future::IntoServiceFuture::new(future)
175    }
176}
177
178// for `axum::serve(listener, handler)`
179#[cfg(all(feature = "tokio", any(feature = "http1", feature = "http2")))]
180const _: () = {
181    use crate::serve;
182
183    impl<H, T, S, L> Service<serve::IncomingStream<'_, L>> for HandlerService<H, T, S>
184    where
185        H: Clone,
186        S: Clone,
187        L: serve::Listener,
188    {
189        type Response = Self;
190        type Error = Infallible;
191        type Future = std::future::Ready<Result<Self::Response, Self::Error>>;
192
193        fn poll_ready(&mut self, _cx: &mut Context<'_>) -> Poll<Result<(), Self::Error>> {
194            Poll::Ready(Ok(()))
195        }
196
197        fn call(&mut self, _req: serve::IncomingStream<'_, L>) -> Self::Future {
198            std::future::ready(Ok(self.clone()))
199        }
200    }
201};