Skip to main content

axum/routing/
method_routing.rs

1//! Route to services and handlers based on HTTP methods.
2
3use super::{future::InfallibleRouteFuture, IntoMakeService};
4#[cfg(feature = "tokio")]
5use crate::extract::connect_info::IntoMakeServiceWithConnectInfo;
6use crate::{
7    body::{Body, Bytes, HttpBody},
8    boxed::BoxedIntoRoute,
9    error_handling::{HandleError, HandleErrorLayer},
10    handler::Handler,
11    http::{Method, StatusCode},
12    response::Response,
13    routing::{future::RouteFuture, Fallback, MethodFilter, Route},
14};
15use axum_core::{extract::Request, response::IntoResponse, BoxError};
16use bytes::BytesMut;
17use std::{
18    borrow::Cow,
19    convert::Infallible,
20    fmt,
21    task::{Context, Poll},
22};
23use tower::service_fn;
24use tower_layer::Layer;
25use tower_service::Service;
26
27macro_rules! top_level_service_fn {
28    (
29        $name:ident, GET
30    ) => {
31        top_level_service_fn!(
32            /// Route `GET` requests to the given service.
33            ///
34            /// # Example
35            ///
36            /// ```rust
37            /// use axum::{
38            ///     extract::Request,
39            ///     Router,
40            ///     routing::get_service,
41            ///     body::Body,
42            /// };
43            /// use http::Response;
44            /// use std::convert::Infallible;
45            ///
46            /// let service = tower::service_fn(|request: Request| async {
47            ///     Ok::<_, Infallible>(Response::new(Body::empty()))
48            /// });
49            ///
50            /// // Requests to `GET /` will go to `service`.
51            /// let app = Router::new().route("/", get_service(service));
52            /// # let _: Router = app;
53            /// ```
54            ///
55            /// Note that `get` routes will also be called for `HEAD` requests but will have
56            /// the response body removed. Make sure to add explicit `HEAD` routes
57            /// afterwards.
58            $name,
59            GET
60        );
61    };
62
63    (
64        $name:ident, CONNECT
65    ) => {
66        top_level_service_fn!(
67            /// Route `CONNECT` requests to the given service.
68            ///
69            /// See [`MethodFilter::CONNECT`] for when you'd want to use this,
70            /// and [`get_service`] for an example.
71            $name,
72            CONNECT
73        );
74    };
75
76    (
77        $name:ident, $method:ident
78    ) => {
79        top_level_service_fn!(
80            #[doc = concat!("Route `", stringify!($method) ,"` requests to the given service.")]
81            ///
82            /// See [`get_service`] for an example.
83            $name,
84            $method
85        );
86    };
87
88    (
89        $(#[$m:meta])+
90        $name:ident, $method:ident
91    ) => {
92        $(#[$m])+
93        pub fn $name<T, S>(svc: T) -> MethodRouter<S, T::Error>
94        where
95            T: Service<Request> + Clone + Send + Sync + 'static,
96            T::Response: IntoResponse + 'static,
97            T::Future: Send + 'static,
98            S: Clone,
99        {
100            on_service(MethodFilter::$method, svc)
101        }
102    };
103}
104
105macro_rules! top_level_handler_fn {
106    (
107        $name:ident, GET
108    ) => {
109        top_level_handler_fn!(
110            /// Route `GET` requests to the given handler.
111            ///
112            /// # Example
113            ///
114            /// ```rust
115            /// use axum::{
116            ///     routing::get,
117            ///     Router,
118            /// };
119            ///
120            /// async fn handler() {}
121            ///
122            /// // Requests to `GET /` will go to `handler`.
123            /// let app = Router::new().route("/", get(handler));
124            /// # let _: Router = app;
125            /// ```
126            ///
127            /// Note that `get` routes will also be called for `HEAD` requests but will have
128            /// the response body removed. Make sure to add explicit `HEAD` routes
129            /// afterwards.
130            $name,
131            GET
132        );
133    };
134
135    (
136        $name:ident, CONNECT
137    ) => {
138        top_level_handler_fn!(
139            /// Route `CONNECT` requests to the given handler.
140            ///
141            /// See [`MethodFilter::CONNECT`] for when you'd want to use this,
142            /// and [`get`] for an example.
143            $name,
144            CONNECT
145        );
146    };
147
148    (
149        $name:ident, $method:ident
150    ) => {
151        top_level_handler_fn!(
152            #[doc = concat!("Route `", stringify!($method) ,"` requests to the given handler.")]
153            ///
154            /// See [`get`] for an example.
155            $name,
156            $method
157        );
158    };
159
160    (
161        $(#[$m:meta])+
162        $name:ident, $method:ident
163    ) => {
164        $(#[$m])+
165        pub fn $name<H, T, S>(handler: H) -> MethodRouter<S, Infallible>
166        where
167            H: Handler<T, S>,
168            T: 'static,
169            S: Clone + Send + Sync + 'static,
170        {
171            on(MethodFilter::$method, handler)
172        }
173    };
174}
175
176macro_rules! chained_service_fn {
177    (
178        $name:ident, GET
179    ) => {
180        chained_service_fn!(
181            /// Chain an additional service that will only accept `GET` requests.
182            ///
183            /// # Example
184            ///
185            /// ```rust
186            /// use axum::{
187            ///     extract::Request,
188            ///     Router,
189            ///     routing::post_service,
190            ///     body::Body,
191            /// };
192            /// use http::Response;
193            /// use std::convert::Infallible;
194            ///
195            /// let service = tower::service_fn(|request: Request| async {
196            ///     Ok::<_, Infallible>(Response::new(Body::empty()))
197            /// });
198            ///
199            /// let other_service = tower::service_fn(|request: Request| async {
200            ///     Ok::<_, Infallible>(Response::new(Body::empty()))
201            /// });
202            ///
203            /// // Requests to `POST /` will go to `service` and `GET /` will go to
204            /// // `other_service`.
205            /// let app = Router::new().route("/", post_service(service).get_service(other_service));
206            /// # let _: Router = app;
207            /// ```
208            ///
209            /// Note that `get` routes will also be called for `HEAD` requests but will have
210            /// the response body removed. Make sure to add explicit `HEAD` routes
211            /// afterwards.
212            $name,
213            GET
214        );
215    };
216
217    (
218        $name:ident, CONNECT
219    ) => {
220        chained_service_fn!(
221            /// Chain an additional service that will only accept `CONNECT` requests.
222            ///
223            /// See [`MethodFilter::CONNECT`] for when you'd want to use this,
224            /// and [`MethodRouter::get_service`] for an example.
225            $name,
226            CONNECT
227        );
228    };
229
230    (
231        $name:ident, $method:ident
232    ) => {
233        chained_service_fn!(
234            #[doc = concat!("Chain an additional service that will only accept `", stringify!($method),"` requests.")]
235            ///
236            /// See [`MethodRouter::get_service`] for an example.
237            $name,
238            $method
239        );
240    };
241
242    (
243        $(#[$m:meta])+
244        $name:ident, $method:ident
245    ) => {
246        $(#[$m])+
247        #[track_caller]
248        pub fn $name<T>(self, svc: T) -> Self
249        where
250            T: Service<Request, Error = E>
251                + Clone
252                + Send
253                + Sync
254                + 'static,
255            T::Response: IntoResponse + 'static,
256            T::Future: Send + 'static,
257        {
258            self.on_service(MethodFilter::$method, svc)
259        }
260    };
261}
262
263macro_rules! chained_handler_fn {
264    (
265        $name:ident, GET
266    ) => {
267        chained_handler_fn!(
268            /// Chain an additional handler that will only accept `GET` requests.
269            ///
270            /// # Example
271            ///
272            /// ```rust
273            /// use axum::{routing::post, Router};
274            ///
275            /// async fn handler() {}
276            ///
277            /// async fn other_handler() {}
278            ///
279            /// // Requests to `POST /` will go to `handler` and `GET /` will go to
280            /// // `other_handler`.
281            /// let app = Router::new().route("/", post(handler).get(other_handler));
282            /// # let _: Router = app;
283            /// ```
284            ///
285            /// Note that `get` routes will also be called for `HEAD` requests but will have
286            /// the response body removed. Make sure to add explicit `HEAD` routes
287            /// afterwards.
288            $name,
289            GET
290        );
291    };
292
293    (
294        $name:ident, CONNECT
295    ) => {
296        chained_handler_fn!(
297            /// Chain an additional handler that will only accept `CONNECT` requests.
298            ///
299            /// See [`MethodFilter::CONNECT`] for when you'd want to use this,
300            /// and [`MethodRouter::get`] for an example.
301            $name,
302            CONNECT
303        );
304    };
305
306    (
307        $name:ident, $method:ident
308    ) => {
309        chained_handler_fn!(
310            #[doc = concat!("Chain an additional handler that will only accept `", stringify!($method),"` requests.")]
311            ///
312            /// See [`MethodRouter::get`] for an example.
313            $name,
314            $method
315        );
316    };
317
318    (
319        $(#[$m:meta])+
320        $name:ident, $method:ident
321    ) => {
322        $(#[$m])+
323        #[track_caller]
324        pub fn $name<H, T>(self, handler: H) -> Self
325        where
326            H: Handler<T, S>,
327            T: 'static,
328            S: Send + Sync + 'static,
329        {
330            self.on(MethodFilter::$method, handler)
331        }
332    };
333}
334
335top_level_service_fn!(connect_service, CONNECT);
336top_level_service_fn!(delete_service, DELETE);
337top_level_service_fn!(get_service, GET);
338top_level_service_fn!(head_service, HEAD);
339top_level_service_fn!(options_service, OPTIONS);
340top_level_service_fn!(patch_service, PATCH);
341top_level_service_fn!(post_service, POST);
342top_level_service_fn!(put_service, PUT);
343top_level_service_fn!(trace_service, TRACE);
344top_level_service_fn!(query_service, QUERY);
345
346/// Route requests with the given method to the service.
347///
348/// # Example
349///
350/// ```rust
351/// use axum::{
352///     extract::Request,
353///     routing::on,
354///     Router,
355///     body::Body,
356///     routing::{MethodFilter, on_service},
357/// };
358/// use http::Response;
359/// use std::convert::Infallible;
360///
361/// let service = tower::service_fn(|request: Request| async {
362///     Ok::<_, Infallible>(Response::new(Body::empty()))
363/// });
364///
365/// // Requests to `POST /` will go to `service`.
366/// let app = Router::new().route("/", on_service(MethodFilter::POST, service));
367/// # let _: Router = app;
368/// ```
369pub fn on_service<T, S>(filter: MethodFilter, svc: T) -> MethodRouter<S, T::Error>
370where
371    T: Service<Request> + Clone + Send + Sync + 'static,
372    T::Response: IntoResponse + 'static,
373    T::Future: Send + 'static,
374    S: Clone,
375{
376    MethodRouter::new().on_service(filter, svc)
377}
378
379/// Route requests to the given service regardless of its method.
380///
381/// # Example
382///
383/// ```rust
384/// use axum::{
385///     extract::Request,
386///     Router,
387///     routing::any_service,
388///     body::Body,
389/// };
390/// use http::Response;
391/// use std::convert::Infallible;
392///
393/// let service = tower::service_fn(|request: Request| async {
394///     Ok::<_, Infallible>(Response::new(Body::empty()))
395/// });
396///
397/// // All requests to `/` will go to `service`.
398/// let app = Router::new().route("/", any_service(service));
399/// # let _: Router = app;
400/// ```
401///
402/// Additional methods can still be chained:
403///
404/// ```rust
405/// use axum::{
406///     extract::Request,
407///     Router,
408///     routing::any_service,
409///     body::Body,
410/// };
411/// use http::Response;
412/// use std::convert::Infallible;
413///
414/// let service = tower::service_fn(|request: Request| async {
415///     # Ok::<_, Infallible>(Response::new(Body::empty()))
416///     // ...
417/// });
418///
419/// let other_service = tower::service_fn(|request: Request| async {
420///     # Ok::<_, Infallible>(Response::new(Body::empty()))
421///     // ...
422/// });
423///
424/// // `POST /` goes to `other_service`. All other requests go to `service`
425/// let app = Router::new().route("/", any_service(service).post_service(other_service));
426/// # let _: Router = app;
427/// ```
428pub fn any_service<T, S>(svc: T) -> MethodRouter<S, T::Error>
429where
430    T: Service<Request> + Clone + Send + Sync + 'static,
431    T::Response: IntoResponse + 'static,
432    T::Future: Send + 'static,
433    S: Clone,
434{
435    MethodRouter::new()
436        .fallback_service(svc)
437        .skip_allow_header()
438}
439
440top_level_handler_fn!(connect, CONNECT);
441top_level_handler_fn!(delete, DELETE);
442top_level_handler_fn!(get, GET);
443top_level_handler_fn!(head, HEAD);
444top_level_handler_fn!(options, OPTIONS);
445top_level_handler_fn!(patch, PATCH);
446top_level_handler_fn!(post, POST);
447top_level_handler_fn!(put, PUT);
448top_level_handler_fn!(trace, TRACE);
449top_level_handler_fn!(query, QUERY);
450
451/// Route requests with the given method to the handler.
452///
453/// # Example
454///
455/// ```rust
456/// use axum::{
457///     routing::on,
458///     Router,
459///     routing::MethodFilter,
460/// };
461///
462/// async fn handler() {}
463///
464/// // Requests to `POST /` will go to `handler`.
465/// let app = Router::new().route("/", on(MethodFilter::POST, handler));
466/// # let _: Router = app;
467/// ```
468pub fn on<H, T, S>(filter: MethodFilter, handler: H) -> MethodRouter<S, Infallible>
469where
470    H: Handler<T, S>,
471    T: 'static,
472    S: Clone + Send + Sync + 'static,
473{
474    MethodRouter::new().on(filter, handler)
475}
476
477/// Route requests with the given handler regardless of the method.
478///
479/// # Example
480///
481/// ```rust
482/// use axum::{
483///     routing::any,
484///     Router,
485/// };
486///
487/// async fn handler() {}
488///
489/// // All requests to `/` will go to `handler`.
490/// let app = Router::new().route("/", any(handler));
491/// # let _: Router = app;
492/// ```
493///
494/// Additional methods can still be chained:
495///
496/// ```rust
497/// use axum::{
498///     routing::any,
499///     Router,
500/// };
501///
502/// async fn handler() {}
503///
504/// async fn other_handler() {}
505///
506/// // `POST /` goes to `other_handler`. All other requests go to `handler`
507/// let app = Router::new().route("/", any(handler).post(other_handler));
508/// # let _: Router = app;
509/// ```
510pub fn any<H, T, S>(handler: H) -> MethodRouter<S, Infallible>
511where
512    H: Handler<T, S>,
513    T: 'static,
514    S: Clone + Send + Sync + 'static,
515{
516    MethodRouter::new().fallback(handler).skip_allow_header()
517}
518
519/// A [`Service`] that accepts requests based on a [`MethodFilter`] and
520/// allows chaining additional handlers and services.
521///
522/// # When does `MethodRouter` implement [`Service`]?
523///
524/// Whether or not `MethodRouter` implements [`Service`] depends on the state type it requires.
525///
526/// ```
527/// use tower::Service;
528/// use axum::{routing::get, extract::{State, Request}, body::Body};
529///
530/// // this `MethodRouter` doesn't require any state, i.e. the state is `()`,
531/// let method_router = get(|| async {});
532/// // and thus it implements `Service`
533/// assert_service(method_router);
534///
535/// // this requires a `String` and doesn't implement `Service`
536/// let method_router = get(|_: State<String>| async {});
537/// // until you provide the `String` with `.with_state(...)`
538/// let method_router_with_state = method_router.with_state(String::new());
539/// // and then it implements `Service`
540/// assert_service(method_router_with_state);
541///
542/// // helper to check that a value implements `Service`
543/// fn assert_service<S>(service: S)
544/// where
545///     S: Service<Request>,
546/// {}
547/// ```
548#[must_use]
549pub struct MethodRouter<S = (), E = Infallible> {
550    get: MethodEndpoint<S, E>,
551    head: MethodEndpoint<S, E>,
552    delete: MethodEndpoint<S, E>,
553    options: MethodEndpoint<S, E>,
554    patch: MethodEndpoint<S, E>,
555    post: MethodEndpoint<S, E>,
556    put: MethodEndpoint<S, E>,
557    trace: MethodEndpoint<S, E>,
558    connect: MethodEndpoint<S, E>,
559    query: MethodEndpoint<S, E>,
560    fallback: Fallback<S, E>,
561    allow_header: AllowHeader,
562}
563
564#[derive(Clone, Debug)]
565enum AllowHeader {
566    /// No `Allow` header value has been built-up yet. This is the default state
567    None,
568    /// Don't set an `Allow` header. This is used when `any` or `any_service` are called.
569    Skip,
570    /// The current value of the `Allow` header.
571    Bytes(BytesMut),
572}
573
574impl AllowHeader {
575    fn merge(self, other: Self) -> Self {
576        match (self, other) {
577            (Self::Skip, _) | (_, Self::Skip) => Self::Skip,
578            (Self::None, Self::None) => Self::None,
579            (Self::None, Self::Bytes(pick)) | (Self::Bytes(pick), Self::None) => Self::Bytes(pick),
580            (mut this @ Self::Bytes(_), Self::Bytes(b)) => {
581                match std::str::from_utf8(&b) {
582                    Ok(methods) => {
583                        for method in methods.split(',') {
584                            append_allow_header(&mut this, method);
585                        }
586                    }
587                    Err(_) => {
588                        #[cfg(debug_assertions)]
589                        panic!("`allow_header` contained invalid utf-8. This should never happen")
590                    }
591                }
592                this
593            }
594        }
595    }
596}
597
598impl<S, E> fmt::Debug for MethodRouter<S, E> {
599    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
600        f.debug_struct("MethodRouter")
601            .field("get", &self.get)
602            .field("head", &self.head)
603            .field("delete", &self.delete)
604            .field("options", &self.options)
605            .field("patch", &self.patch)
606            .field("post", &self.post)
607            .field("put", &self.put)
608            .field("trace", &self.trace)
609            .field("connect", &self.connect)
610            .field("query", &self.query)
611            .field("fallback", &self.fallback)
612            .field("allow_header", &self.allow_header)
613            .finish()
614    }
615}
616
617impl<S> MethodRouter<S, Infallible>
618where
619    S: Clone,
620{
621    /// Chain an additional handler that will accept requests matching the given
622    /// `MethodFilter`.
623    ///
624    /// # Example
625    ///
626    /// ```rust
627    /// use axum::{
628    ///     routing::get,
629    ///     Router,
630    ///     routing::MethodFilter
631    /// };
632    ///
633    /// async fn handler() {}
634    ///
635    /// async fn other_handler() {}
636    ///
637    /// // Requests to `GET /` will go to `handler` and `DELETE /` will go to
638    /// // `other_handler`
639    /// let app = Router::new().route("/", get(handler).on(MethodFilter::DELETE, other_handler));
640    /// # let _: Router = app;
641    /// ```
642    #[track_caller]
643    pub fn on<H, T>(self, filter: MethodFilter, handler: H) -> Self
644    where
645        H: Handler<T, S>,
646        T: 'static,
647        S: Send + Sync + 'static,
648    {
649        self.on_endpoint(
650            filter,
651            &MethodEndpoint::BoxedHandler(BoxedIntoRoute::from_handler(handler)),
652        )
653    }
654
655    chained_handler_fn!(connect, CONNECT);
656    chained_handler_fn!(delete, DELETE);
657    chained_handler_fn!(get, GET);
658    chained_handler_fn!(head, HEAD);
659    chained_handler_fn!(options, OPTIONS);
660    chained_handler_fn!(patch, PATCH);
661    chained_handler_fn!(post, POST);
662    chained_handler_fn!(put, PUT);
663    chained_handler_fn!(trace, TRACE);
664    chained_handler_fn!(query, QUERY);
665
666    /// Add a fallback [`Handler`] to the router.
667    pub fn fallback<H, T>(mut self, handler: H) -> Self
668    where
669        H: Handler<T, S>,
670        T: 'static,
671        S: Send + Sync + 'static,
672    {
673        self.fallback = Fallback::BoxedHandler(BoxedIntoRoute::from_handler(handler));
674        self
675    }
676
677    /// Get a [`MethodFilter`] for the methods that this `MethodRouter` has
678    /// custom code for.
679    ///
680    /// Note that `MethodRouter`'s [`Service`] implementation never fails (it
681    /// always creates an HTTP response) based on which HTTP method was used.
682    /// However, the information which methods have the default behavior of
683    /// returning HTTP 405 is stored, and can be queried with this method.
684    ///
685    /// Returns `None` if the `MethodRouter` was constructed with [`any`] or
686    /// has had a [`fallback`][Self::fallback] set.
687    pub fn method_filter(&self) -> Option<MethodFilter> {
688        let Self {
689            get,
690            head,
691            delete,
692            options,
693            patch,
694            post,
695            put,
696            trace,
697            connect,
698            query,
699            fallback,
700            allow_header: _,
701        } = self;
702
703        if !fallback.is_default() {
704            return None;
705        }
706
707        let filter = [
708            (get, MethodFilter::GET),
709            (head, MethodFilter::HEAD),
710            (delete, MethodFilter::DELETE),
711            (options, MethodFilter::OPTIONS),
712            (patch, MethodFilter::PATCH),
713            (post, MethodFilter::POST),
714            (put, MethodFilter::PUT),
715            (trace, MethodFilter::TRACE),
716            (connect, MethodFilter::CONNECT),
717            (query, MethodFilter::QUERY),
718        ]
719        .into_iter()
720        .filter_map(|(ep, f)| ep.is_some().then_some(f))
721        .reduce(MethodFilter::or)
722        .expect("can't create a MethodRouter with all-default handlers");
723
724        Some(filter)
725    }
726
727    /// Add a fallback [`Handler`] if no custom one has been provided.
728    pub(crate) fn default_fallback<H, T>(self, handler: H) -> Self
729    where
730        H: Handler<T, S>,
731        T: 'static,
732        S: Send + Sync + 'static,
733    {
734        match self.fallback {
735            Fallback::Default(_) => self.fallback(handler),
736            _ => self,
737        }
738    }
739}
740
741impl MethodRouter<(), Infallible> {
742    /// Convert the router into a [`MakeService`].
743    ///
744    /// This allows you to serve a single `MethodRouter` if you don't need any
745    /// routing based on the path:
746    ///
747    /// ```rust
748    /// use axum::{
749    ///     handler::Handler,
750    ///     http::{Uri, Method},
751    ///     response::IntoResponse,
752    ///     routing::get,
753    /// };
754    /// use std::net::SocketAddr;
755    ///
756    /// async fn handler(method: Method, uri: Uri, body: String) -> String {
757    ///     format!("received `{method} {uri}` with body `{body:?}`")
758    /// }
759    ///
760    /// let router = get(handler).post(handler);
761    ///
762    /// # async {
763    /// let listener = tokio::net::TcpListener::bind("0.0.0.0:3000").await.unwrap();
764    /// axum::serve(listener, router.into_make_service()).await;
765    /// # };
766    /// ```
767    ///
768    /// [`MakeService`]: tower::make::MakeService
769    #[must_use]
770    pub fn into_make_service(self) -> IntoMakeService<Self> {
771        IntoMakeService::new(self.with_state(()))
772    }
773
774    /// Convert the router into a [`MakeService`] which stores information
775    /// about the incoming connection.
776    ///
777    /// See [`Router::into_make_service_with_connect_info`] for more details.
778    ///
779    /// ```rust
780    /// use axum::{
781    ///     handler::Handler,
782    ///     response::IntoResponse,
783    ///     extract::ConnectInfo,
784    ///     routing::get,
785    /// };
786    /// use std::net::SocketAddr;
787    ///
788    /// async fn handler(ConnectInfo(addr): ConnectInfo<SocketAddr>) -> String {
789    ///     format!("Hello {addr}")
790    /// }
791    ///
792    /// let router = get(handler).post(handler);
793    ///
794    /// # async {
795    /// let listener = tokio::net::TcpListener::bind("0.0.0.0:3000").await.unwrap();
796    /// axum::serve(listener, router.into_make_service()).await;
797    /// # };
798    /// ```
799    ///
800    /// [`MakeService`]: tower::make::MakeService
801    /// [`Router::into_make_service_with_connect_info`]: crate::routing::Router::into_make_service_with_connect_info
802    #[cfg(feature = "tokio")]
803    #[must_use]
804    pub fn into_make_service_with_connect_info<C>(self) -> IntoMakeServiceWithConnectInfo<Self, C> {
805        IntoMakeServiceWithConnectInfo::new(self.with_state(()))
806    }
807}
808
809impl<S, E> MethodRouter<S, E>
810where
811    S: Clone,
812{
813    /// Create a default `MethodRouter` that will respond with `405 Method Not Allowed` to all
814    /// requests.
815    pub fn new() -> Self {
816        let fallback = Route::new(service_fn(|_: Request| async {
817            Ok(StatusCode::METHOD_NOT_ALLOWED)
818        }));
819
820        Self {
821            get: MethodEndpoint::None,
822            head: MethodEndpoint::None,
823            delete: MethodEndpoint::None,
824            options: MethodEndpoint::None,
825            patch: MethodEndpoint::None,
826            post: MethodEndpoint::None,
827            put: MethodEndpoint::None,
828            trace: MethodEndpoint::None,
829            connect: MethodEndpoint::None,
830            query: MethodEndpoint::None,
831            allow_header: AllowHeader::None,
832            fallback: Fallback::Default(fallback),
833        }
834    }
835
836    /// Provide the state for the router.
837    pub fn with_state<S2>(self, state: S) -> MethodRouter<S2, E> {
838        MethodRouter {
839            get: self.get.with_state(&state),
840            head: self.head.with_state(&state),
841            delete: self.delete.with_state(&state),
842            options: self.options.with_state(&state),
843            patch: self.patch.with_state(&state),
844            post: self.post.with_state(&state),
845            put: self.put.with_state(&state),
846            trace: self.trace.with_state(&state),
847            connect: self.connect.with_state(&state),
848            query: self.query.with_state(&state),
849            allow_header: self.allow_header,
850            fallback: self.fallback.with_state(state),
851        }
852    }
853
854    /// Chain an additional service that will accept requests matching the given
855    /// `MethodFilter`.
856    ///
857    /// # Example
858    ///
859    /// ```rust
860    /// use axum::{
861    ///     extract::Request,
862    ///     Router,
863    ///     routing::{MethodFilter, on_service},
864    ///     body::Body,
865    /// };
866    /// use http::Response;
867    /// use std::convert::Infallible;
868    ///
869    /// let service = tower::service_fn(|request: Request| async {
870    ///     Ok::<_, Infallible>(Response::new(Body::empty()))
871    /// });
872    ///
873    /// // Requests to `DELETE /` will go to `service`
874    /// let app = Router::new().route("/", on_service(MethodFilter::DELETE, service));
875    /// # let _: Router = app;
876    /// ```
877    #[track_caller]
878    pub fn on_service<T>(self, filter: MethodFilter, svc: T) -> Self
879    where
880        T: Service<Request, Error = E> + Clone + Send + Sync + 'static,
881        T::Response: IntoResponse + 'static,
882        T::Future: Send + 'static,
883    {
884        self.on_endpoint(filter, &MethodEndpoint::Route(Route::new(svc)))
885    }
886
887    #[track_caller]
888    fn on_endpoint(mut self, filter: MethodFilter, endpoint: &MethodEndpoint<S, E>) -> Self {
889        // written as a separate function to generate less IR
890        #[track_caller]
891        fn set_endpoint<S, E>(
892            method_name: &str,
893            out: &mut MethodEndpoint<S, E>,
894            endpoint: &MethodEndpoint<S, E>,
895            endpoint_filter: MethodFilter,
896            filter: MethodFilter,
897            allow_header: &mut AllowHeader,
898            methods: &[&'static str],
899        ) where
900            MethodEndpoint<S, E>: Clone,
901            S: Clone,
902        {
903            if endpoint_filter.contains(filter) {
904                if out.is_some() {
905                    panic!(
906                        "Overlapping method route. Cannot add two method routes that both handle \
907                         `{method_name}`",
908                    );
909                }
910                *out = endpoint.clone();
911                for method in methods {
912                    append_allow_header(allow_header, method);
913                }
914            }
915        }
916
917        set_endpoint(
918            "GET",
919            &mut self.get,
920            endpoint,
921            filter,
922            MethodFilter::GET,
923            &mut self.allow_header,
924            &["GET", "HEAD"],
925        );
926
927        set_endpoint(
928            "HEAD",
929            &mut self.head,
930            endpoint,
931            filter,
932            MethodFilter::HEAD,
933            &mut self.allow_header,
934            &["HEAD"],
935        );
936
937        set_endpoint(
938            "TRACE",
939            &mut self.trace,
940            endpoint,
941            filter,
942            MethodFilter::TRACE,
943            &mut self.allow_header,
944            &["TRACE"],
945        );
946
947        set_endpoint(
948            "PUT",
949            &mut self.put,
950            endpoint,
951            filter,
952            MethodFilter::PUT,
953            &mut self.allow_header,
954            &["PUT"],
955        );
956
957        set_endpoint(
958            "POST",
959            &mut self.post,
960            endpoint,
961            filter,
962            MethodFilter::POST,
963            &mut self.allow_header,
964            &["POST"],
965        );
966
967        set_endpoint(
968            "PATCH",
969            &mut self.patch,
970            endpoint,
971            filter,
972            MethodFilter::PATCH,
973            &mut self.allow_header,
974            &["PATCH"],
975        );
976
977        set_endpoint(
978            "OPTIONS",
979            &mut self.options,
980            endpoint,
981            filter,
982            MethodFilter::OPTIONS,
983            &mut self.allow_header,
984            &["OPTIONS"],
985        );
986
987        set_endpoint(
988            "DELETE",
989            &mut self.delete,
990            endpoint,
991            filter,
992            MethodFilter::DELETE,
993            &mut self.allow_header,
994            &["DELETE"],
995        );
996
997        set_endpoint(
998            "CONNECT",
999            &mut self.connect,
1000            endpoint,
1001            filter,
1002            MethodFilter::CONNECT,
1003            &mut self.allow_header,
1004            &["CONNECT"],
1005        );
1006
1007        set_endpoint(
1008            "QUERY",
1009            &mut self.query,
1010            endpoint,
1011            filter,
1012            MethodFilter::QUERY,
1013            &mut self.allow_header,
1014            &["QUERY"],
1015        );
1016
1017        self
1018    }
1019
1020    chained_service_fn!(connect_service, CONNECT);
1021    chained_service_fn!(delete_service, DELETE);
1022    chained_service_fn!(get_service, GET);
1023    chained_service_fn!(head_service, HEAD);
1024    chained_service_fn!(options_service, OPTIONS);
1025    chained_service_fn!(patch_service, PATCH);
1026    chained_service_fn!(post_service, POST);
1027    chained_service_fn!(put_service, PUT);
1028    chained_service_fn!(trace_service, TRACE);
1029    chained_service_fn!(query_service, QUERY);
1030
1031    #[doc = include_str!("../docs/method_routing/fallback.md")]
1032    pub fn fallback_service<T>(mut self, svc: T) -> Self
1033    where
1034        T: Service<Request, Error = E> + Clone + Send + Sync + 'static,
1035        T::Response: IntoResponse + 'static,
1036        T::Future: Send + 'static,
1037    {
1038        self.fallback = Fallback::Service(Route::new(svc));
1039        self
1040    }
1041
1042    #[doc = include_str!("../docs/method_routing/layer.md")]
1043    pub fn layer<L, NewError>(self, layer: L) -> MethodRouter<S, NewError>
1044    where
1045        L: Layer<Route<E>> + Clone + Send + Sync + 'static,
1046        L::Service: Service<Request> + Clone + Send + Sync + 'static,
1047        <L::Service as Service<Request>>::Response: IntoResponse + 'static,
1048        <L::Service as Service<Request>>::Error: Into<NewError> + 'static,
1049        <L::Service as Service<Request>>::Future: Send + 'static,
1050        E: 'static,
1051        S: 'static,
1052        NewError: 'static,
1053    {
1054        let layer_fn = move |route: Route<E>| route.layer(layer.clone());
1055
1056        MethodRouter {
1057            get: self.get.map(layer_fn.clone()),
1058            head: self.head.map(layer_fn.clone()),
1059            delete: self.delete.map(layer_fn.clone()),
1060            options: self.options.map(layer_fn.clone()),
1061            patch: self.patch.map(layer_fn.clone()),
1062            post: self.post.map(layer_fn.clone()),
1063            put: self.put.map(layer_fn.clone()),
1064            trace: self.trace.map(layer_fn.clone()),
1065            connect: self.connect.map(layer_fn.clone()),
1066            query: self.query.map(layer_fn.clone()),
1067            fallback: self.fallback.map(layer_fn),
1068            allow_header: self.allow_header,
1069        }
1070    }
1071
1072    #[doc = include_str!("../docs/method_routing/route_layer.md")]
1073    #[track_caller]
1074    pub fn route_layer<L>(mut self, layer: L) -> Self
1075    where
1076        L: Layer<Route<E>> + Clone + Send + Sync + 'static,
1077        L::Service: Service<Request, Error = E> + Clone + Send + Sync + 'static,
1078        <L::Service as Service<Request>>::Response: IntoResponse + 'static,
1079        <L::Service as Service<Request>>::Future: Send + 'static,
1080        E: 'static,
1081        S: 'static,
1082    {
1083        if self.get.is_none()
1084            && self.head.is_none()
1085            && self.delete.is_none()
1086            && self.options.is_none()
1087            && self.patch.is_none()
1088            && self.post.is_none()
1089            && self.put.is_none()
1090            && self.trace.is_none()
1091            && self.connect.is_none()
1092            && self.query.is_none()
1093        {
1094            panic!(
1095                "Adding a route_layer before any routes is a no-op. \
1096                 Add the routes you want the layer to apply to first."
1097            );
1098        }
1099
1100        let layer_fn = move |svc| Route::new(layer.layer(svc));
1101
1102        self.get = self.get.map(layer_fn.clone());
1103        self.head = self.head.map(layer_fn.clone());
1104        self.delete = self.delete.map(layer_fn.clone());
1105        self.options = self.options.map(layer_fn.clone());
1106        self.patch = self.patch.map(layer_fn.clone());
1107        self.post = self.post.map(layer_fn.clone());
1108        self.put = self.put.map(layer_fn.clone());
1109        self.trace = self.trace.map(layer_fn.clone());
1110        self.connect = self.connect.map(layer_fn.clone());
1111        self.query = self.query.map(layer_fn);
1112
1113        self
1114    }
1115
1116    pub(crate) fn merge_for_path(
1117        mut self,
1118        path: Option<&str>,
1119        other: Self,
1120    ) -> Result<Self, Cow<'static, str>> {
1121        // written using inner functions to generate less IR
1122        fn merge_inner<S, E>(
1123            path: Option<&str>,
1124            name: &str,
1125            first: MethodEndpoint<S, E>,
1126            second: MethodEndpoint<S, E>,
1127        ) -> Result<MethodEndpoint<S, E>, Cow<'static, str>> {
1128            match (first, second) {
1129                (MethodEndpoint::None, MethodEndpoint::None) => Ok(MethodEndpoint::None),
1130                (pick, MethodEndpoint::None) | (MethodEndpoint::None, pick) => Ok(pick),
1131                _ => {
1132                    if let Some(path) = path {
1133                        Err(format!(
1134                            "Overlapping method route. Handler for `{name} {path}` already exists"
1135                        )
1136                        .into())
1137                    } else {
1138                        Err(format!(
1139                            "Overlapping method route. Cannot merge two method routes that both \
1140                             define `{name}`"
1141                        )
1142                        .into())
1143                    }
1144                }
1145            }
1146        }
1147
1148        self.get = merge_inner(path, "GET", self.get, other.get)?;
1149        self.head = merge_inner(path, "HEAD", self.head, other.head)?;
1150        self.delete = merge_inner(path, "DELETE", self.delete, other.delete)?;
1151        self.options = merge_inner(path, "OPTIONS", self.options, other.options)?;
1152        self.patch = merge_inner(path, "PATCH", self.patch, other.patch)?;
1153        self.post = merge_inner(path, "POST", self.post, other.post)?;
1154        self.put = merge_inner(path, "PUT", self.put, other.put)?;
1155        self.trace = merge_inner(path, "TRACE", self.trace, other.trace)?;
1156        self.connect = merge_inner(path, "CONNECT", self.connect, other.connect)?;
1157        self.query = merge_inner(path, "QUERY", self.query, other.query)?;
1158
1159        self.fallback = self
1160            .fallback
1161            .merge(other.fallback)
1162            .ok_or("Cannot merge two `MethodRouter`s that both have a fallback")?;
1163
1164        self.allow_header = self.allow_header.merge(other.allow_header);
1165
1166        Ok(self)
1167    }
1168
1169    #[doc = include_str!("../docs/method_routing/merge.md")]
1170    #[track_caller]
1171    pub fn merge(self, other: Self) -> Self {
1172        match self.merge_for_path(None, other) {
1173            Ok(t) => t,
1174            // not using unwrap or unwrap_or_else to get a clean panic message + the right location
1175            Err(e) => panic!("{e}"),
1176        }
1177    }
1178
1179    /// Apply a [`HandleErrorLayer`].
1180    ///
1181    /// This is a convenience method for doing `self.layer(HandleErrorLayer::new(f))`.
1182    pub fn handle_error<F, T>(self, f: F) -> MethodRouter<S, Infallible>
1183    where
1184        F: Clone + Send + Sync + 'static,
1185        HandleError<Route<E>, F, T>: Service<Request, Error = Infallible>,
1186        <HandleError<Route<E>, F, T> as Service<Request>>::Future: Send,
1187        <HandleError<Route<E>, F, T> as Service<Request>>::Response: IntoResponse + Send,
1188        T: 'static,
1189        E: 'static,
1190        S: 'static,
1191    {
1192        self.layer(HandleErrorLayer::new(f))
1193    }
1194
1195    fn skip_allow_header(mut self) -> Self {
1196        self.allow_header = AllowHeader::Skip;
1197        self
1198    }
1199
1200    pub(crate) fn call_with_state(&self, req: Request, state: S) -> RouteFuture<E> {
1201        macro_rules! call {
1202            (
1203                $req:expr,
1204                $method_variant:ident,
1205                $svc:expr
1206            ) => {
1207                if *req.method() == Method::$method_variant {
1208                    match $svc {
1209                        MethodEndpoint::None => {}
1210                        MethodEndpoint::Route(route) => {
1211                            return route.clone().oneshot_inner_owned($req);
1212                        }
1213                        MethodEndpoint::BoxedHandler(handler) => {
1214                            let route = handler.clone().into_route(state);
1215                            return route.oneshot_inner_owned($req);
1216                        }
1217                    }
1218                }
1219            };
1220        }
1221
1222        // written with a pattern match like this to ensure we call all routes
1223        let Self {
1224            get,
1225            head,
1226            delete,
1227            options,
1228            patch,
1229            post,
1230            put,
1231            trace,
1232            connect,
1233            query,
1234            fallback,
1235            allow_header,
1236        } = self;
1237
1238        call!(req, HEAD, head);
1239        call!(req, HEAD, get);
1240        call!(req, GET, get);
1241        call!(req, POST, post);
1242        call!(req, OPTIONS, options);
1243        call!(req, PATCH, patch);
1244        call!(req, PUT, put);
1245        call!(req, DELETE, delete);
1246        call!(req, TRACE, trace);
1247        call!(req, CONNECT, connect);
1248        call!(req, QUERY, query);
1249
1250        let future = fallback.clone().call_with_state(req, state);
1251
1252        match allow_header {
1253            AllowHeader::None => future.allow_header(Bytes::new()),
1254            AllowHeader::Skip => future,
1255            AllowHeader::Bytes(allow_header) => future.allow_header(allow_header.clone().freeze()),
1256        }
1257    }
1258}
1259
1260fn append_allow_header(allow_header: &mut AllowHeader, method: &str) {
1261    match allow_header {
1262        AllowHeader::None => {
1263            *allow_header = AllowHeader::Bytes(BytesMut::from(method));
1264        }
1265        AllowHeader::Skip => {}
1266        AllowHeader::Bytes(allow_header) => {
1267            if let Ok(s) = std::str::from_utf8(allow_header) {
1268                if !s.contains(method) {
1269                    allow_header.extend_from_slice(b",");
1270                    allow_header.extend_from_slice(method.as_bytes());
1271                }
1272            } else {
1273                #[cfg(debug_assertions)]
1274                panic!("`allow_header` contained invalid utf-8. This should never happen")
1275            }
1276        }
1277    }
1278}
1279
1280impl<S, E> Clone for MethodRouter<S, E> {
1281    fn clone(&self) -> Self {
1282        Self {
1283            get: self.get.clone(),
1284            head: self.head.clone(),
1285            delete: self.delete.clone(),
1286            options: self.options.clone(),
1287            patch: self.patch.clone(),
1288            post: self.post.clone(),
1289            put: self.put.clone(),
1290            trace: self.trace.clone(),
1291            connect: self.connect.clone(),
1292            query: self.query.clone(),
1293            fallback: self.fallback.clone(),
1294            allow_header: self.allow_header.clone(),
1295        }
1296    }
1297}
1298
1299impl<S, E> Default for MethodRouter<S, E>
1300where
1301    S: Clone,
1302{
1303    fn default() -> Self {
1304        Self::new()
1305    }
1306}
1307
1308enum MethodEndpoint<S, E> {
1309    None,
1310    Route(Route<E>),
1311    BoxedHandler(BoxedIntoRoute<S, E>),
1312}
1313
1314impl<S, E> MethodEndpoint<S, E>
1315where
1316    S: Clone,
1317{
1318    fn is_some(&self) -> bool {
1319        matches!(self, Self::Route(_) | Self::BoxedHandler(_))
1320    }
1321
1322    fn is_none(&self) -> bool {
1323        matches!(self, Self::None)
1324    }
1325
1326    fn map<F, E2>(self, f: F) -> MethodEndpoint<S, E2>
1327    where
1328        S: 'static,
1329        E: 'static,
1330        F: FnOnce(Route<E>) -> Route<E2> + Clone + Send + Sync + 'static,
1331        E2: 'static,
1332    {
1333        match self {
1334            Self::None => MethodEndpoint::None,
1335            Self::Route(route) => MethodEndpoint::Route(f(route)),
1336            Self::BoxedHandler(handler) => MethodEndpoint::BoxedHandler(handler.map(f)),
1337        }
1338    }
1339
1340    fn with_state<S2>(self, state: &S) -> MethodEndpoint<S2, E> {
1341        match self {
1342            Self::None => MethodEndpoint::None,
1343            Self::Route(route) => MethodEndpoint::Route(route),
1344            Self::BoxedHandler(handler) => MethodEndpoint::Route(handler.into_route(state.clone())),
1345        }
1346    }
1347}
1348
1349impl<S, E> Clone for MethodEndpoint<S, E> {
1350    fn clone(&self) -> Self {
1351        match self {
1352            Self::None => Self::None,
1353            Self::Route(inner) => Self::Route(inner.clone()),
1354            Self::BoxedHandler(inner) => Self::BoxedHandler(inner.clone()),
1355        }
1356    }
1357}
1358
1359impl<S, E> fmt::Debug for MethodEndpoint<S, E> {
1360    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1361        match self {
1362            Self::None => f.debug_tuple("None").finish(),
1363            Self::Route(inner) => inner.fmt(f),
1364            Self::BoxedHandler(_) => f.debug_tuple("BoxedHandler").finish(),
1365        }
1366    }
1367}
1368
1369impl<B, E> Service<Request<B>> for MethodRouter<(), E>
1370where
1371    B: HttpBody<Data = Bytes> + Send + 'static,
1372    B::Error: Into<BoxError>,
1373{
1374    type Response = Response;
1375    type Error = E;
1376    type Future = RouteFuture<E>;
1377
1378    #[inline]
1379    fn poll_ready(&mut self, _cx: &mut Context<'_>) -> Poll<Result<(), Self::Error>> {
1380        Poll::Ready(Ok(()))
1381    }
1382
1383    #[inline]
1384    fn call(&mut self, req: Request<B>) -> Self::Future {
1385        let req = req.map(Body::new);
1386        self.call_with_state(req, ())
1387    }
1388}
1389
1390#[diagnostic::do_not_recommend]
1391impl<S> Handler<(), S> for MethodRouter<S>
1392where
1393    S: Clone + 'static,
1394{
1395    type Future = InfallibleRouteFuture;
1396
1397    fn call(self, req: Request, state: S) -> Self::Future {
1398        InfallibleRouteFuture::new(self.call_with_state(req, state))
1399    }
1400}
1401
1402// for `axum::serve(listener, router)`
1403#[cfg(all(feature = "tokio", any(feature = "http1", feature = "http2")))]
1404const _: () = {
1405    use crate::serve;
1406
1407    impl<L> Service<serve::IncomingStream<'_, L>> for MethodRouter<()>
1408    where
1409        L: serve::Listener,
1410    {
1411        type Response = Self;
1412        type Error = Infallible;
1413        type Future = std::future::Ready<Result<Self::Response, Self::Error>>;
1414
1415        fn poll_ready(&mut self, _cx: &mut Context<'_>) -> Poll<Result<(), Self::Error>> {
1416            Poll::Ready(Ok(()))
1417        }
1418
1419        fn call(&mut self, _req: serve::IncomingStream<'_, L>) -> Self::Future {
1420            std::future::ready(Ok(self.clone().with_state(())))
1421        }
1422    }
1423};
1424
1425#[cfg(test)]
1426mod tests {
1427    use super::*;
1428    use crate::{extract::State, handler::HandlerWithoutStateExt};
1429    use http::{header::ALLOW, HeaderMap};
1430    use http_body_util::BodyExt;
1431    use std::time::Duration;
1432    use tower::ServiceExt;
1433    use tower_http::{
1434        services::fs::ServeDir, timeout::TimeoutLayer, validate_request::ValidateRequestHeaderLayer,
1435    };
1436
1437    #[crate::test]
1438    async fn method_not_allowed_by_default() {
1439        let mut svc = MethodRouter::new();
1440        let (status, _, body) = call(Method::GET, &mut svc).await;
1441        assert_eq!(status, StatusCode::METHOD_NOT_ALLOWED);
1442        assert!(body.is_empty());
1443    }
1444
1445    #[crate::test]
1446    async fn get_service_fn() {
1447        async fn handle(_req: Request) -> Result<Response<Body>, Infallible> {
1448            Ok(Response::new(Body::from("ok")))
1449        }
1450
1451        let mut svc = get_service(service_fn(handle));
1452
1453        let (status, _, body) = call(Method::GET, &mut svc).await;
1454        assert_eq!(status, StatusCode::OK);
1455        assert_eq!(body, "ok");
1456    }
1457
1458    #[crate::test]
1459    async fn get_handler() {
1460        let mut svc = MethodRouter::new().get(ok);
1461        let (status, _, body) = call(Method::GET, &mut svc).await;
1462        assert_eq!(status, StatusCode::OK);
1463        assert_eq!(body, "ok");
1464    }
1465
1466    #[crate::test]
1467    async fn get_accepts_head() {
1468        let mut svc = MethodRouter::new().get(ok);
1469        let (status, _, body) = call(Method::HEAD, &mut svc).await;
1470        assert_eq!(status, StatusCode::OK);
1471        assert!(body.is_empty());
1472    }
1473
1474    #[crate::test]
1475    async fn head_takes_precedence_over_get() {
1476        let mut svc = MethodRouter::new().head(created).get(ok);
1477        let (status, _, body) = call(Method::HEAD, &mut svc).await;
1478        assert_eq!(status, StatusCode::CREATED);
1479        assert!(body.is_empty());
1480    }
1481
1482    #[crate::test]
1483    async fn merge() {
1484        let mut svc = get(ok).merge(post(ok)).merge(connect(ok));
1485
1486        let (status, _, _) = call(Method::GET, &mut svc).await;
1487        assert_eq!(status, StatusCode::OK);
1488
1489        let (status, _, _) = call(Method::POST, &mut svc).await;
1490        assert_eq!(status, StatusCode::OK);
1491
1492        let (status, _, _) = call(Method::CONNECT, &mut svc).await;
1493        assert_eq!(status, StatusCode::OK);
1494    }
1495
1496    #[allow(deprecated)]
1497    #[crate::test]
1498    async fn layer() {
1499        let mut svc = MethodRouter::new()
1500            .get(|| async { std::future::pending::<()>().await })
1501            .layer(ValidateRequestHeaderLayer::bearer("password"));
1502
1503        // method with route
1504        let (status, _, _) = call(Method::GET, &mut svc).await;
1505        assert_eq!(status, StatusCode::UNAUTHORIZED);
1506
1507        // method without route
1508        let (status, _, _) = call(Method::DELETE, &mut svc).await;
1509        assert_eq!(status, StatusCode::UNAUTHORIZED);
1510    }
1511
1512    #[allow(deprecated)]
1513    #[crate::test]
1514    async fn route_layer() {
1515        let mut svc = MethodRouter::new()
1516            .get(|| async { std::future::pending::<()>().await })
1517            .route_layer(ValidateRequestHeaderLayer::bearer("password"));
1518
1519        // method with route
1520        let (status, _, _) = call(Method::GET, &mut svc).await;
1521        assert_eq!(status, StatusCode::UNAUTHORIZED);
1522
1523        // method without route
1524        let (status, _, _) = call(Method::DELETE, &mut svc).await;
1525        assert_eq!(status, StatusCode::METHOD_NOT_ALLOWED);
1526    }
1527
1528    #[allow(dead_code, deprecated)]
1529    async fn building_complex_router() {
1530        let app = crate::Router::new().route(
1531            "/",
1532            // use the all the things 💣️
1533            get(ok)
1534                .post(ok)
1535                .route_layer(ValidateRequestHeaderLayer::bearer("password"))
1536                .merge(delete_service(ServeDir::new(".")))
1537                .fallback(|| async { StatusCode::NOT_FOUND })
1538                .put(ok)
1539                .layer(TimeoutLayer::with_status_code(
1540                    StatusCode::REQUEST_TIMEOUT,
1541                    Duration::from_secs(10),
1542                )),
1543        );
1544
1545        let listener = tokio::net::TcpListener::bind("0.0.0.0:0").await.unwrap();
1546        crate::serve(listener, app).await;
1547    }
1548
1549    #[crate::test]
1550    async fn sets_allow_header() {
1551        let mut svc = MethodRouter::new().put(ok).patch(ok);
1552        let (status, headers, _) = call(Method::GET, &mut svc).await;
1553        assert_eq!(status, StatusCode::METHOD_NOT_ALLOWED);
1554        assert_eq!(headers[ALLOW], "PUT,PATCH");
1555    }
1556
1557    #[crate::test]
1558    async fn sets_allow_header_get_head() {
1559        let mut svc = MethodRouter::new().get(ok).head(ok);
1560        let (status, headers, _) = call(Method::PUT, &mut svc).await;
1561        assert_eq!(status, StatusCode::METHOD_NOT_ALLOWED);
1562        assert_eq!(headers[ALLOW], "GET,HEAD");
1563    }
1564
1565    #[crate::test]
1566    async fn empty_allow_header_by_default() {
1567        let mut svc = MethodRouter::new();
1568        let (status, headers, _) = call(Method::PATCH, &mut svc).await;
1569        assert_eq!(status, StatusCode::METHOD_NOT_ALLOWED);
1570        assert_eq!(headers[ALLOW], "");
1571    }
1572
1573    #[crate::test]
1574    async fn allow_header_when_merging() {
1575        let a = put(ok).patch(ok);
1576        let b = get(ok).head(ok);
1577        let mut svc = a.merge(b);
1578
1579        let (status, headers, _) = call(Method::DELETE, &mut svc).await;
1580        assert_eq!(status, StatusCode::METHOD_NOT_ALLOWED);
1581        assert_eq!(headers[ALLOW], "PUT,PATCH,GET,HEAD");
1582    }
1583
1584    #[crate::test]
1585    async fn allow_header_merging_get_into_head() {
1586        let a = get(ok);
1587        let b = head(created);
1588        let mut svc = a.merge(b);
1589
1590        let (status, headers, _) = call(Method::DELETE, &mut svc).await;
1591        assert_eq!(status, StatusCode::METHOD_NOT_ALLOWED);
1592        assert_eq!(headers[ALLOW], "GET,HEAD");
1593    }
1594
1595    #[crate::test]
1596    async fn allow_header_any() {
1597        let mut svc = any(ok);
1598
1599        let (status, headers, _) = call(Method::GET, &mut svc).await;
1600        assert_eq!(status, StatusCode::OK);
1601        assert!(!headers.contains_key(ALLOW));
1602    }
1603
1604    #[crate::test]
1605    async fn allow_header_with_fallback() {
1606        let mut svc = MethodRouter::new()
1607            .get(ok)
1608            .fallback(|| async { (StatusCode::METHOD_NOT_ALLOWED, "Method not allowed") });
1609
1610        let (status, headers, _) = call(Method::DELETE, &mut svc).await;
1611        assert_eq!(status, StatusCode::METHOD_NOT_ALLOWED);
1612        assert_eq!(headers[ALLOW], "GET,HEAD");
1613    }
1614
1615    #[crate::test]
1616    async fn allow_header_with_fallback_that_sets_allow() {
1617        async fn fallback(method: Method) -> Response {
1618            if method == Method::POST {
1619                "OK".into_response()
1620            } else {
1621                (
1622                    StatusCode::METHOD_NOT_ALLOWED,
1623                    [(ALLOW, "GET,POST")],
1624                    "Method not allowed",
1625                )
1626                    .into_response()
1627            }
1628        }
1629
1630        let mut svc = MethodRouter::new().get(ok).fallback(fallback);
1631
1632        let (status, _, _) = call(Method::GET, &mut svc).await;
1633        assert_eq!(status, StatusCode::OK);
1634
1635        let (status, _, _) = call(Method::POST, &mut svc).await;
1636        assert_eq!(status, StatusCode::OK);
1637
1638        let (status, headers, _) = call(Method::DELETE, &mut svc).await;
1639        assert_eq!(status, StatusCode::METHOD_NOT_ALLOWED);
1640        assert_eq!(headers[ALLOW], "GET,POST");
1641    }
1642
1643    #[crate::test]
1644    async fn allow_header_noop_middleware() {
1645        let mut svc = MethodRouter::new()
1646            .get(ok)
1647            .layer(tower::layer::util::Identity::new());
1648
1649        let (status, headers, _) = call(Method::DELETE, &mut svc).await;
1650        assert_eq!(status, StatusCode::METHOD_NOT_ALLOWED);
1651        assert_eq!(headers[ALLOW], "GET,HEAD");
1652    }
1653
1654    #[crate::test]
1655    #[should_panic(
1656        expected = "Overlapping method route. Cannot add two method routes that both handle `GET`"
1657    )]
1658    async fn handler_overlaps() {
1659        let _: MethodRouter<()> = get(ok).get(ok);
1660    }
1661
1662    #[crate::test]
1663    #[should_panic(
1664        expected = "Overlapping method route. Cannot add two method routes that both handle `POST`"
1665    )]
1666    async fn service_overlaps() {
1667        let _: MethodRouter<()> = post_service(ok.into_service()).post_service(ok.into_service());
1668    }
1669
1670    #[crate::test]
1671    async fn get_head_does_not_overlap() {
1672        let _: MethodRouter<()> = get(ok).head(ok);
1673    }
1674
1675    #[crate::test]
1676    async fn head_get_does_not_overlap() {
1677        let _: MethodRouter<()> = head(ok).get(ok);
1678    }
1679
1680    #[crate::test]
1681    async fn accessing_state() {
1682        let mut svc = MethodRouter::new()
1683            .get(|State(state): State<&'static str>| async move { state })
1684            .with_state("state");
1685
1686        let (status, _, text) = call(Method::GET, &mut svc).await;
1687
1688        assert_eq!(status, StatusCode::OK);
1689        assert_eq!(text, "state");
1690    }
1691
1692    #[crate::test]
1693    async fn fallback_accessing_state() {
1694        let mut svc = MethodRouter::new()
1695            .fallback(|State(state): State<&'static str>| async move { state })
1696            .with_state("state");
1697
1698        let (status, _, text) = call(Method::GET, &mut svc).await;
1699
1700        assert_eq!(status, StatusCode::OK);
1701        assert_eq!(text, "state");
1702    }
1703
1704    #[crate::test]
1705    async fn merge_accessing_state() {
1706        let one = get(|State(state): State<&'static str>| async move { state });
1707        let two = post(|State(state): State<&'static str>| async move { state });
1708
1709        let mut svc = one.merge(two).with_state("state");
1710
1711        let (status, _, text) = call(Method::GET, &mut svc).await;
1712        assert_eq!(status, StatusCode::OK);
1713        assert_eq!(text, "state");
1714
1715        let (status, _, _) = call(Method::POST, &mut svc).await;
1716        assert_eq!(status, StatusCode::OK);
1717        assert_eq!(text, "state");
1718    }
1719
1720    #[test]
1721    fn method_filter() {
1722        let router: MethodRouter = get(|| async {});
1723        assert_eq!(router.method_filter(), Some(MethodFilter::GET));
1724
1725        let router: MethodRouter = get(|| async {}).head(|| async {}).post(|| async {});
1726        assert_eq!(
1727            router.method_filter(),
1728            Some(
1729                MethodFilter::GET
1730                    .or(MethodFilter::HEAD)
1731                    .or(MethodFilter::POST)
1732            )
1733        );
1734
1735        let router: MethodRouter = any(|| async {});
1736        assert_eq!(router.method_filter(), None);
1737    }
1738
1739    async fn call<S>(method: Method, svc: &mut S) -> (StatusCode, HeaderMap, String)
1740    where
1741        S: Service<Request, Error = Infallible>,
1742        S::Response: IntoResponse,
1743    {
1744        let request = Request::builder()
1745            .uri("/")
1746            .method(method)
1747            .body(Body::empty())
1748            .unwrap();
1749        let response = svc
1750            .ready()
1751            .await
1752            .unwrap()
1753            .call(request)
1754            .await
1755            .unwrap()
1756            .into_response();
1757        let (parts, body) = response.into_parts();
1758        let body =
1759            String::from_utf8(BodyExt::collect(body).await.unwrap().to_bytes().to_vec()).unwrap();
1760        (parts.status, parts.headers, body)
1761    }
1762
1763    async fn ok() -> (StatusCode, &'static str) {
1764        (StatusCode::OK, "ok")
1765    }
1766
1767    async fn created() -> (StatusCode, &'static str) {
1768        (StatusCode::CREATED, "created")
1769    }
1770}