Skip to main content

axum/routing/
nested.rs

1use std::{
2    convert::Infallible,
3    fmt::Debug,
4    task::{Context, Poll},
5};
6
7use axum_core::{
8    body::Body,
9    extract::Request as AxumRequest,
10    response::{IntoResponse, Response},
11};
12use http::Request;
13use http_body::Body as HttpBody;
14use tower::{Layer, Service};
15
16use super::{route::RouteFuture, Endpoint, Route, Router};
17
18#[derive(Clone)]
19pub(crate) enum NestedRootMarker {
20    Root,
21    Slash,
22}
23
24/// This enum controls behavior of which routes will be registered with a nested router.
25///
26/// We consider here two routes - _root_ and _slash_. For example if we nest a [`Nested`] router
27/// under prefix `/prefix`, the two routes are:
28/// - `/prefix` is the _root_ route and
29/// - `/prefix/` is the _slash_ route.
30#[allow(clippy::large_enum_variant)]
31pub(super) enum RootNestBehavior<S> {
32    /// The slash route is configured on the nested router's `/` and root route is explicitly given
33    ExplicitRoot(Endpoint<S>),
34    /// The root route is handled with the nested router's `/` and slash route is handled by the
35    /// fallback.
36    RootOnly,
37    /// The slash route is handled with the nested router's `/` and root route is handled by the
38    /// fallback.
39    SlashOnly,
40    /// Both the root and slash routes are handled with the nested router's `/`.
41    RootAndSlash,
42}
43
44impl<S> Clone for RootNestBehavior<S> {
45    fn clone(&self) -> Self {
46        match self {
47            Self::RootOnly => Self::RootOnly,
48            Self::ExplicitRoot(endpoint) => Self::ExplicitRoot(endpoint.clone()),
49            Self::RootAndSlash => Self::RootAndSlash,
50            Self::SlashOnly => Self::SlashOnly,
51        }
52    }
53}
54
55impl<S> Debug for RootNestBehavior<S> {
56    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
57        match self {
58            Self::RootOnly => write!(f, "RootOnly"),
59            Self::ExplicitRoot(endpoint) => f.debug_tuple("ExplicitRoot").field(endpoint).finish(),
60            Self::RootAndSlash => write!(f, "RootAndSlash"),
61            Self::SlashOnly => write!(f, "SlashOnly"),
62        }
63    }
64}
65
66/// The nested router type for composing routers.
67///
68/// This type can be [`nest`]ed into other [`Router`]s. It can be created by some methods on
69/// `Router` such as `route_root`.
70///
71/// [`nest`]: Router::nest()
72/// [`route_root`]: Router::route_root()
73#[must_use]
74pub struct Nested<S = ()> {
75    router: Router<S>,
76    root: RootNestBehavior<S>,
77}
78
79impl<S> Clone for Nested<S> {
80    fn clone(&self) -> Self {
81        Self {
82            router: self.router.clone(),
83            root: self.root.clone(),
84        }
85    }
86}
87
88impl<S> Debug for Nested<S> {
89    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
90        f.debug_struct("Nested")
91            .field("router", &self.router)
92            .field("root", &self.root)
93            .finish()
94    }
95}
96
97impl<S> From<Router<S>> for Nested<S> {
98    fn from(router: Router<S>) -> Self {
99        Self {
100            router,
101            root: RootNestBehavior::RootOnly,
102        }
103    }
104}
105
106impl<S> Nested<S> {
107    pub(super) fn new(router: Router<S>, root: RootNestBehavior<S>) -> Self {
108        Self { router, root }
109    }
110
111    pub(super) fn into_inner(self) -> (Router<S>, RootNestBehavior<S>) {
112        let Self { router, root } = self;
113        (router, root)
114    }
115
116    /// Apply a [`tower::Layer`] to all routes in the router.
117    ///
118    /// This can be used to add additional processing to a request for a group
119    /// of routes including the root route.
120    ///
121    /// See [`Router::layer`] for more details.
122    pub fn layer<L>(self, layer: L) -> Self
123    where
124        L: Layer<Route> + Clone + Send + Sync + 'static,
125        L::Service: Service<AxumRequest> + Clone + Send + Sync + 'static,
126        <L::Service as Service<AxumRequest>>::Response: IntoResponse + 'static,
127        <L::Service as Service<AxumRequest>>::Error: Into<Infallible> + 'static,
128        <L::Service as Service<AxumRequest>>::Future: Send + 'static,
129        S: Clone + Send + Sync + 'static,
130    {
131        let Self { router, root } = self;
132
133        let router = router.layer(layer.clone());
134
135        let root = match root {
136            RootNestBehavior::ExplicitRoot(endpoint) => {
137                RootNestBehavior::ExplicitRoot(endpoint.layer(layer))
138            }
139            root @ (RootNestBehavior::RootOnly
140            | RootNestBehavior::RootAndSlash
141            | RootNestBehavior::SlashOnly) => root,
142        };
143
144        Self { router, root }
145    }
146}
147
148impl<B> Service<Request<B>> for Nested<()>
149where
150    B: HttpBody<Data = bytes::Bytes> + Send + 'static,
151    B::Error: Into<axum_core::BoxError>,
152{
153    type Response = Response;
154    type Error = Infallible;
155    type Future = RouteFuture<Infallible>;
156
157    #[inline]
158    fn poll_ready(&mut self, _: &mut Context<'_>) -> Poll<Result<(), Self::Error>> {
159        Poll::Ready(Ok(()))
160    }
161
162    #[inline]
163    fn call(&mut self, req: Request<B>) -> Self::Future {
164        let call_fallback = |req: AxumRequest| {
165            self.router
166                .inner
167                .catch_all_fallback
168                .clone()
169                .call_with_state(req, ())
170        };
171
172        let mut req = req.map(Body::new);
173
174        if req.uri().path() == "/" {
175            let is_root_path = matches!(
176                req.extensions_mut().remove::<NestedRootMarker>(),
177                Some(NestedRootMarker::Root)
178            );
179            match (&self.root, is_root_path) {
180                (RootNestBehavior::RootAndSlash, _)
181                | (RootNestBehavior::RootOnly, true)
182                | (RootNestBehavior::SlashOnly | RootNestBehavior::ExplicitRoot(_), false) => {
183                    // Continue, the `/` path will match the correct handler.
184                }
185                (RootNestBehavior::ExplicitRoot(endpoint), true) => {
186                    return match endpoint {
187                        Endpoint::MethodRouter(method_router) => {
188                            method_router.call_with_state(req, ())
189                        }
190                        Endpoint::Route(route) => route.clone().call_owned(req),
191                    };
192                }
193                (RootNestBehavior::RootOnly, false) | (RootNestBehavior::SlashOnly, true) => {
194                    return call_fallback(req);
195                }
196            }
197        }
198
199        self.router.call_with_state(req, ())
200    }
201}