1use self::{
4 future::RouteFuture, nested::RootNestBehavior, not_found::NotFound, path_router::PathRouter,
5};
6#[cfg(feature = "tokio")]
7use crate::extract::connect_info::IntoMakeServiceWithConnectInfo;
8#[cfg(feature = "matched-path")]
9use crate::extract::MatchedPath;
10use crate::{
11 body::{Body, HttpBody},
12 boxed::BoxedIntoRoute,
13 handler::Handler,
14 util::try_downcast,
15};
16use axum_core::{
17 extract::Request,
18 response::{IntoResponse, Response},
19};
20use std::{
21 convert::Infallible,
22 fmt,
23 marker::PhantomData,
24 sync::Arc,
25 task::{Context, Poll},
26};
27use tower::service_fn;
28use tower_layer::{layer_fn, Layer};
29use tower_service::Service;
30
31pub mod future;
32pub mod method_routing;
33
34mod into_make_service;
35mod method_filter;
36mod nested;
37mod not_found;
38pub(crate) mod path_router;
39mod route;
40mod strip_prefix;
41#[cfg(test)]
42mod tests;
43pub(crate) mod url_params;
44
45pub use self::{
46 into_make_service::IntoMakeService, method_filter::MethodFilter, nested::Nested, route::Route,
47};
48
49pub use self::method_routing::{
50 any, any_service, connect, connect_service, delete, delete_service, get, get_service, head,
51 head_service, on, on_service, options, options_service, patch, patch_service, post,
52 post_service, put, put_service, query, query_service, trace, trace_service, MethodRouter,
53};
54
55macro_rules! panic_on_err {
56 ($expr:expr) => {
57 match $expr {
58 Ok(x) => x,
59 Err(err) => panic!("{err}"),
60 }
61 };
62}
63
64const TAKE_ONCE_ROUTE_PANIC_MSG: &str =
65 "TakeOnceRoute called more than once; if this was not triggered by an intentional test, this should never happen. Please file an issue.";
66
67fn take_route_or_internal_error(service: &mut Option<Route>) -> Route {
68 service.take().unwrap_or_else(|| {
69 if cfg!(debug_assertions) {
70 panic!("{TAKE_ONCE_ROUTE_PANIC_MSG}");
71 }
72
73 Route::new(service_fn(|_req: Request| async move {
74 Ok::<_, Infallible>(http::StatusCode::INTERNAL_SERVER_ERROR.into_response())
75 }))
76 })
77}
78
79#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
80pub(crate) struct RouteId(usize);
81
82#[must_use]
90pub struct Router<S = ()> {
91 inner: Arc<RouterInner<S>>,
92 finalized: bool,
95}
96
97impl<S> Clone for Router<S> {
98 fn clone(&self) -> Self {
99 Self {
100 inner: Arc::clone(&self.inner),
101 finalized: self.finalized,
102 }
103 }
104}
105
106struct RouterInner<S> {
107 path_router: PathRouter<S>,
108 default_fallback: bool,
109 catch_all_fallback: Fallback<S>,
110}
111
112impl<S> Default for Router<S>
113where
114 S: Clone + Send + Sync + 'static,
115{
116 fn default() -> Self {
117 Self::new()
118 }
119}
120
121impl<S> fmt::Debug for Router<S> {
122 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
123 f.debug_struct("Router")
124 .field("path_router", &self.inner.path_router)
125 .field("default_fallback", &self.inner.default_fallback)
126 .field("catch_all_fallback", &self.inner.catch_all_fallback)
127 .field("finalized", &self.finalized)
128 .finish()
129 }
130}
131
132pub(crate) const NEST_TAIL_PARAM: &str = "__private__axum_nest_tail_param";
133#[cfg(feature = "matched-path")]
134pub(crate) const NEST_TAIL_PARAM_CAPTURE: &str = "/{*__private__axum_nest_tail_param}";
135pub(crate) const FALLBACK_PARAM: &str = "__private__axum_fallback";
136pub(crate) const FALLBACK_PARAM_PATH: &str = "/{*__private__axum_fallback}";
137
138macro_rules! map_inner {
139 ( $self_:ident, $inner:pat_param => $expr:expr) => {{
140 let $inner = $self_.into_inner();
141 Router {
142 inner: Arc::new($expr),
143 finalized: false,
144 }
145 }};
146}
147
148macro_rules! tap_inner {
149 ( $self_:ident, mut $inner:ident => { $($stmt:stmt)* } ) => {
150 #[allow(redundant_semicolons)]
151 {
152 let mut $inner = $self_.into_inner();
153 $($stmt)*;
154 Router {
155 inner: Arc::new($inner),
156 finalized: false,
157 }
158 }
159 };
160}
161
162impl<S> Router<S>
163where
164 S: Clone + Send + Sync + 'static,
165{
166 pub fn new() -> Self {
171 Self {
172 inner: Arc::new(RouterInner {
173 path_router: Default::default(),
174 default_fallback: true,
175 catch_all_fallback: Fallback::Default(Route::new(NotFound)),
176 }),
177 finalized: false,
178 }
179 }
180
181 fn into_inner(self) -> RouterInner<S> {
182 match Arc::try_unwrap(self.inner) {
183 Ok(inner) => inner,
184 Err(arc) => RouterInner {
185 path_router: arc.path_router.clone(),
186 default_fallback: arc.default_fallback,
187 catch_all_fallback: arc.catch_all_fallback.clone(),
188 },
189 }
190 }
191
192 #[doc = include_str!("../docs/routing/route.md")]
193 #[track_caller]
194 pub fn route(self, path: &str, method_router: MethodRouter<S>) -> Self {
195 tap_inner!(self, mut this => {
196 panic_on_err!(this.path_router.route(path, method_router));
197 })
198 }
199
200 #[doc = include_str!("../docs/routing/route_service.md")]
201 pub fn route_service<T>(self, path: &str, service: T) -> Self
202 where
203 T: Service<Request, Error = Infallible> + Clone + Send + Sync + 'static,
204 T::Response: IntoResponse,
205 T::Future: Send + 'static,
206 {
207 let Err(service) = try_downcast::<Self, _>(service) else {
208 panic!(
209 "Invalid route: `Router::route_service` cannot be used with `Router`s. \
210 Use `Router::nest` instead"
211 );
212 };
213
214 tap_inner!(self, mut this => {
215 panic_on_err!(this.path_router.route_service(path, service));
216 })
217 }
218
219 #[doc = include_str!("../docs/routing/nest.md")]
220 #[doc(alias = "scope")] #[track_caller]
222 pub fn nest(self, path: &str, router: impl Into<Nested<S>>) -> Self {
223 if path.is_empty() || path == "/" {
224 panic!("Nesting at the root is no longer supported. Use merge instead.");
225 }
226
227 let (router, root) = router.into().into_inner();
228
229 let RouterInner {
230 path_router,
231 default_fallback: _,
232 catch_all_fallback: _,
236 } = router.into_inner();
237
238 tap_inner!(self, mut this => {
239 panic_on_err!(
240 this
241 .path_router
242 .nest(
243 path,
244 path_router,
245 &root,
246 )
247 );
248 })
249 }
250
251 #[track_caller]
253 pub fn nest_service<T>(self, path: &str, service: T) -> Self
254 where
255 T: Service<Request, Error = Infallible> + Clone + Send + Sync + 'static,
256 T::Response: IntoResponse,
257 T::Future: Send + 'static,
258 {
259 if path.is_empty() || path == "/" {
260 panic!("Nesting at the root is no longer supported. Use fallback_service instead.");
261 }
262
263 tap_inner!(self, mut this => {
264 panic_on_err!(this.path_router.nest_service(path, service));
265 })
266 }
267
268 pub fn route_root(self, method_router: MethodRouter<S>) -> Nested<S> {
295 Nested::new(
296 self,
297 RootNestBehavior::ExplicitRoot(Endpoint::MethodRouter(method_router)),
298 )
299 }
300
301 pub fn route_root_service<T>(self, service: T) -> Nested<S>
303 where
304 T: Service<Request, Error = Infallible> + Clone + Send + Sync + 'static,
305 T::Response: IntoResponse,
306 T::Future: Send + 'static,
307 {
308 Nested::new(
309 self,
310 RootNestBehavior::ExplicitRoot(Endpoint::Route(Route::new(service))),
311 )
312 }
313
314 pub fn add_slash_handler_to_root_route(self) -> Nested<S> {
324 Nested::new(self, RootNestBehavior::RootAndSlash)
325 }
326
327 pub fn without_slash_route(self) -> Nested<S> {
338 Nested::new(self, RootNestBehavior::RootOnly)
339 }
340
341 pub fn without_root_route(self) -> Nested<S> {
350 Nested::new(self, RootNestBehavior::SlashOnly)
351 }
352
353 #[doc = include_str!("../docs/routing/merge.md")]
354 #[track_caller]
355 pub fn merge<R>(self, other: R) -> Self
356 where
357 R: Into<Self>,
358 {
359 let other: Self = other.into();
360 let RouterInner {
361 path_router,
362 default_fallback,
363 catch_all_fallback,
364 } = other.into_inner();
365
366 map_inner!(self, mut this => {
367 match (this.default_fallback, default_fallback) {
368 (_, true) => {}
371 (true, false) => {
373 this.default_fallback = false;
374 }
375 (false, false) => {
377 panic!("Cannot merge two `Router`s that both have a fallback")
378 }
379 };
380
381 panic_on_err!(this.path_router.merge(path_router));
382
383 this.catch_all_fallback = this
384 .catch_all_fallback
385 .merge(catch_all_fallback)
386 .unwrap_or_else(|| panic!("Cannot merge two `Router`s that both have a fallback"));
387
388 this
389 })
390 }
391
392 #[doc = include_str!("../docs/routing/layer.md")]
393 pub fn layer<L>(self, layer: L) -> Self
394 where
395 L: Layer<Route> + Clone + Send + Sync + 'static,
396 L::Service: Service<Request> + Clone + Send + Sync + 'static,
397 <L::Service as Service<Request>>::Response: IntoResponse + 'static,
398 <L::Service as Service<Request>>::Error: Into<Infallible> + 'static,
399 <L::Service as Service<Request>>::Future: Send + 'static,
400 {
401 map_inner!(self, this => RouterInner {
402 path_router: this.path_router.layer(layer.clone()),
403 default_fallback: this.default_fallback,
404 catch_all_fallback: this.catch_all_fallback.map(|route| route.layer(layer)),
405 })
406 }
407
408 #[doc = include_str!("../docs/routing/route_layer.md")]
409 #[track_caller]
410 pub fn route_layer<L>(self, layer: L) -> Self
411 where
412 L: Layer<Route> + Clone + Send + Sync + 'static,
413 L::Service: Service<Request> + Clone + Send + Sync + 'static,
414 <L::Service as Service<Request>>::Response: IntoResponse + 'static,
415 <L::Service as Service<Request>>::Error: Into<Infallible> + 'static,
416 <L::Service as Service<Request>>::Future: Send + 'static,
417 {
418 map_inner!(self, this => RouterInner {
419 path_router: this.path_router.route_layer(layer),
420 default_fallback: this.default_fallback,
421 catch_all_fallback: this.catch_all_fallback,
422 })
423 }
424
425 #[must_use]
427 pub fn has_routes(&self) -> bool {
428 self.inner.path_router.has_routes()
429 }
430
431 #[track_caller]
432 #[doc = include_str!("../docs/routing/fallback.md")]
433 pub fn fallback<H, T>(self, handler: H) -> Self
434 where
435 H: Handler<T, S>,
436 T: 'static,
437 {
438 tap_inner!(self, mut this => {
439 this.catch_all_fallback =
440 Fallback::BoxedHandler(BoxedIntoRoute::from_handler(handler.clone()));
441 })
442 .fallback_endpoint(Endpoint::MethodRouter(any(handler)))
443 }
444
445 pub fn fallback_service<T>(self, service: T) -> Self
449 where
450 T: Service<Request, Error = Infallible> + Clone + Send + Sync + 'static,
451 T::Response: IntoResponse,
452 T::Future: Send + 'static,
453 {
454 let route = Route::new(service);
455 tap_inner!(self, mut this => {
456 this.catch_all_fallback = Fallback::Service(route.clone());
457 })
458 .fallback_endpoint(Endpoint::Route(route))
459 }
460
461 #[doc = include_str!("../docs/routing/method_not_allowed_fallback.md")]
462 #[allow(clippy::needless_pass_by_value)]
463 pub fn method_not_allowed_fallback<H, T>(self, handler: H) -> Self
464 where
465 H: Handler<T, S>,
466 T: 'static,
467 {
468 tap_inner!(self, mut this => {
469 this.path_router
470 .method_not_allowed_fallback(&handler);
471 })
472 }
473
474 pub fn reset_fallback(self) -> Self {
482 tap_inner!(self, mut this => {
483 this.default_fallback = true;
484 this.catch_all_fallback = Fallback::Default(Route::new(NotFound));
485 })
486 }
487
488 fn fallback_endpoint(self, endpoint: Endpoint<S>) -> Self {
489 tap_inner!(self, mut this => {
496 _ = this.path_router.route_endpoint(
497 "/",
498 endpoint.clone().layer(
499 layer_fn(
500 |service: Route| {
501 let mut service = Some(service);
502 service_fn(
503 #[cfg_attr(not(feature = "matched-path"), allow(unused_mut))]
504 move |mut request: Request| {
505 #[cfg(feature = "matched-path")]
506 request.extensions_mut().remove::<MatchedPath>();
507 let route = take_route_or_internal_error(&mut service);
508 route.oneshot_inner_owned(request)
509 }
510 )
511 }
512 )
513 )
514 );
515
516 _ = this.path_router.route_endpoint(
517 FALLBACK_PARAM_PATH,
518 endpoint.layer(
519 layer_fn(
520 |service: Route| {
521 let mut service = Some(service);
522 service_fn(
523 #[cfg_attr(not(feature = "matched-path"), allow(unused_mut))]
524 move |mut request: Request| {
525 #[cfg(feature = "matched-path")]
526 request.extensions_mut().remove::<MatchedPath>();
527 let route = take_route_or_internal_error(&mut service);
528 route.oneshot_inner_owned(request)
529 }
530 )
531 }
532 )
533 )
534 );
535
536 this.default_fallback = false;
537 })
538 }
539
540 #[doc = include_str!("../docs/routing/with_state.md")]
541 pub fn with_state<S2>(self, state: S) -> Router<S2> {
542 let mut router = map_inner!(self, this => RouterInner {
543 path_router: this.path_router.with_state(state.clone()),
544 default_fallback: this.default_fallback,
545 catch_all_fallback: this.catch_all_fallback.with_state(state),
546 });
547 router.finalized = true;
548 router
549 }
550
551 pub(crate) fn call_with_state(&self, req: Request, state: S) -> RouteFuture<Infallible> {
552 let (req, state) = match self.inner.path_router.call_with_state(req, state) {
553 Ok(future) => return future,
554 Err((req, state)) => (req, state),
555 };
556
557 self.inner
558 .catch_all_fallback
559 .clone()
560 .call_with_state(req, state)
561 }
562
563 pub fn as_service<B>(&mut self) -> RouterAsService<'_, B, S> {
617 RouterAsService {
618 router: self,
619 _marker: PhantomData,
620 }
621 }
622
623 #[must_use]
629 pub fn into_service<B>(self) -> RouterIntoService<B, S> {
630 RouterIntoService {
631 router: self,
632 _marker: PhantomData,
633 }
634 }
635}
636
637impl Router {
638 #[must_use]
657 pub fn into_make_service(self) -> IntoMakeService<Self> {
658 IntoMakeService::new(self.with_state(()))
661 }
662
663 #[doc = include_str!("../docs/routing/into_make_service_with_connect_info.md")]
664 #[cfg(feature = "tokio")]
665 #[must_use]
666 pub fn into_make_service_with_connect_info<C>(self) -> IntoMakeServiceWithConnectInfo<Self, C> {
667 IntoMakeServiceWithConnectInfo::new(self.with_state(()))
670 }
671}
672
673#[cfg(all(feature = "tokio", any(feature = "http1", feature = "http2")))]
675const _: () = {
676 use crate::serve;
677
678 impl<L> Service<serve::IncomingStream<'_, L>> for Router<()>
679 where
680 L: serve::Listener,
681 {
682 type Response = Self;
683 type Error = Infallible;
684 type Future = std::future::Ready<Result<Self::Response, Self::Error>>;
685
686 fn poll_ready(&mut self, _cx: &mut Context<'_>) -> Poll<Result<(), Self::Error>> {
687 Poll::Ready(Ok(()))
688 }
689
690 fn call(&mut self, _req: serve::IncomingStream<'_, L>) -> Self::Future {
691 if !self.finalized {
696 *self = std::mem::take(self).with_state(());
697 }
698 std::future::ready(Ok(self.clone()))
699 }
700 }
701};
702
703impl<B> Service<Request<B>> for Router<()>
704where
705 B: HttpBody<Data = bytes::Bytes> + Send + 'static,
706 B::Error: Into<axum_core::BoxError>,
707{
708 type Response = Response;
709 type Error = Infallible;
710 type Future = RouteFuture<Infallible>;
711
712 #[inline]
713 fn poll_ready(&mut self, _: &mut Context<'_>) -> Poll<Result<(), Self::Error>> {
714 Poll::Ready(Ok(()))
715 }
716
717 #[inline]
718 fn call(&mut self, req: Request<B>) -> Self::Future {
719 let req = req.map(Body::new);
720 self.call_with_state(req, ())
721 }
722}
723
724pub struct RouterAsService<'a, B, S = ()> {
728 router: &'a mut Router<S>,
729 _marker: PhantomData<fn(B)>,
730}
731
732impl<B> Service<Request<B>> for RouterAsService<'_, B, ()>
733where
734 B: HttpBody<Data = bytes::Bytes> + Send + 'static,
735 B::Error: Into<axum_core::BoxError>,
736{
737 type Response = Response;
738 type Error = Infallible;
739 type Future = RouteFuture<Infallible>;
740
741 #[inline]
742 fn poll_ready(&mut self, cx: &mut Context<'_>) -> Poll<Result<(), Self::Error>> {
743 <Router as Service<Request<B>>>::poll_ready(self.router, cx)
744 }
745
746 #[inline]
747 fn call(&mut self, req: Request<B>) -> Self::Future {
748 self.router.call(req)
749 }
750}
751
752impl<B, S> fmt::Debug for RouterAsService<'_, B, S>
753where
754 S: fmt::Debug,
755{
756 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
757 f.debug_struct("RouterAsService")
758 .field("router", &self.router)
759 .finish()
760 }
761}
762
763pub struct RouterIntoService<B, S = ()> {
767 router: Router<S>,
768 _marker: PhantomData<fn(B)>,
769}
770
771impl<B, S> Clone for RouterIntoService<B, S>
772where
773 Router<S>: Clone,
774{
775 fn clone(&self) -> Self {
776 Self {
777 router: self.router.clone(),
778 _marker: PhantomData,
779 }
780 }
781}
782
783impl<B> Service<Request<B>> for RouterIntoService<B, ()>
784where
785 B: HttpBody<Data = bytes::Bytes> + Send + 'static,
786 B::Error: Into<axum_core::BoxError>,
787{
788 type Response = Response;
789 type Error = Infallible;
790 type Future = RouteFuture<Infallible>;
791
792 #[inline]
793 fn poll_ready(&mut self, cx: &mut Context<'_>) -> Poll<Result<(), Self::Error>> {
794 <Router as Service<Request<B>>>::poll_ready(&mut self.router, cx)
795 }
796
797 #[inline]
798 fn call(&mut self, req: Request<B>) -> Self::Future {
799 self.router.call(req)
800 }
801}
802
803impl<B, S> fmt::Debug for RouterIntoService<B, S>
804where
805 S: fmt::Debug,
806{
807 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
808 f.debug_struct("RouterIntoService")
809 .field("router", &self.router)
810 .finish()
811 }
812}
813
814enum Fallback<S, E = Infallible> {
815 Default(Route<E>),
816 Service(Route<E>),
817 BoxedHandler(BoxedIntoRoute<S, E>),
818}
819
820impl<S, E> Fallback<S, E>
821where
822 S: Clone,
823{
824 fn merge(self, other: Self) -> Option<Self> {
825 match (self, other) {
826 (Self::Default(_), pick) | (pick, Self::Default(_)) => Some(pick),
828 _ => None,
830 }
831 }
832
833 fn map<F, E2>(self, f: F) -> Fallback<S, E2>
834 where
835 S: 'static,
836 E: 'static,
837 F: FnOnce(Route<E>) -> Route<E2> + Clone + Send + Sync + 'static,
838 E2: 'static,
839 {
840 match self {
841 Self::Default(route) => Fallback::Default(f(route)),
842 Self::Service(route) => Fallback::Service(f(route)),
843 Self::BoxedHandler(handler) => Fallback::BoxedHandler(handler.map(f)),
844 }
845 }
846
847 fn with_state<S2>(self, state: S) -> Fallback<S2, E> {
848 match self {
849 Self::Default(route) => Fallback::Default(route),
850 Self::Service(route) => Fallback::Service(route),
851 Self::BoxedHandler(handler) => Fallback::Service(handler.into_route(state)),
852 }
853 }
854
855 fn call_with_state(self, req: Request, state: S) -> RouteFuture<E> {
856 match self {
857 Self::Default(route) | Self::Service(route) => route.oneshot_inner_owned(req),
858 Self::BoxedHandler(handler) => {
859 let route = handler.into_route(state);
860 route.oneshot_inner_owned(req)
861 }
862 }
863 }
864
865 fn is_default(&self) -> bool {
866 matches!(self, Self::Default(..))
867 }
868}
869
870impl<S, E> Clone for Fallback<S, E> {
871 fn clone(&self) -> Self {
872 match self {
873 Self::Default(inner) => Self::Default(inner.clone()),
874 Self::Service(inner) => Self::Service(inner.clone()),
875 Self::BoxedHandler(inner) => Self::BoxedHandler(inner.clone()),
876 }
877 }
878}
879
880impl<S, E> fmt::Debug for Fallback<S, E> {
881 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
882 match self {
883 Self::Default(inner) => f.debug_tuple("Default").field(inner).finish(),
884 Self::Service(inner) => f.debug_tuple("Service").field(inner).finish(),
885 Self::BoxedHandler(_) => f.debug_tuple("BoxedHandler").finish(),
886 }
887 }
888}
889
890#[allow(clippy::large_enum_variant)]
891enum Endpoint<S> {
892 MethodRouter(MethodRouter<S>),
893 Route(Route),
894}
895
896impl<S> Endpoint<S>
897where
898 S: Clone + Send + Sync + 'static,
899{
900 fn layer<L>(self, layer: L) -> Self
901 where
902 L: Layer<Route> + Clone + Send + Sync + 'static,
903 L::Service: Service<Request> + Clone + Send + Sync + 'static,
904 <L::Service as Service<Request>>::Response: IntoResponse + 'static,
905 <L::Service as Service<Request>>::Error: Into<Infallible> + 'static,
906 <L::Service as Service<Request>>::Future: Send + 'static,
907 {
908 match self {
909 Self::MethodRouter(method_router) => Self::MethodRouter(method_router.layer(layer)),
910 Self::Route(route) => Self::Route(route.layer(layer)),
911 }
912 }
913}
914
915impl<S> Clone for Endpoint<S> {
916 fn clone(&self) -> Self {
917 match self {
918 Self::MethodRouter(inner) => Self::MethodRouter(inner.clone()),
919 Self::Route(inner) => Self::Route(inner.clone()),
920 }
921 }
922}
923
924impl<S> fmt::Debug for Endpoint<S> {
925 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
926 match self {
927 Self::MethodRouter(method_router) => {
928 f.debug_tuple("MethodRouter").field(method_router).finish()
929 }
930 Self::Route(route) => f.debug_tuple("Route").field(route).finish(),
931 }
932 }
933}
934
935#[test]
936fn traits() {
937 use crate::test_helpers::*;
938 assert_send::<Router<()>>();
939 assert_sync::<Router<()>>();
940 assert_send::<RouterAsService<'static, Body, ()>>();
941 assert_sync::<RouterAsService<'static, Body, ()>>();
942 assert_send::<RouterIntoService<Body, ()>>();
943 assert_sync::<RouterIntoService<Body, ()>>();
944}