1use self::{future::RouteFuture, not_found::NotFound, path_router::PathRouter};
4#[cfg(feature = "tokio")]
5use crate::extract::connect_info::IntoMakeServiceWithConnectInfo;
6use crate::{
7 body::{Body, HttpBody},
8 boxed::BoxedIntoRoute,
9 handler::Handler,
10 util::try_downcast,
11};
12use axum_core::{
13 extract::Request,
14 response::{IntoResponse, Response},
15};
16use std::{
17 convert::Infallible,
18 fmt,
19 marker::PhantomData,
20 sync::Arc,
21 task::{Context, Poll},
22};
23use tower_layer::Layer;
24use tower_service::Service;
25
26pub mod future;
27pub mod method_routing;
28
29mod into_make_service;
30mod method_filter;
31mod not_found;
32pub(crate) mod path_router;
33mod route;
34mod strip_prefix;
35pub(crate) mod url_params;
36
37#[cfg(test)]
38mod tests;
39
40pub use self::{into_make_service::IntoMakeService, method_filter::MethodFilter, route::Route};
41
42pub use self::method_routing::{
43 any, any_service, connect, connect_service, delete, delete_service, get, get_service, head,
44 head_service, on, on_service, options, options_service, patch, patch_service, post,
45 post_service, put, put_service, trace, trace_service, MethodRouter,
46};
47
48macro_rules! panic_on_err {
49 ($expr:expr) => {
50 match $expr {
51 Ok(x) => x,
52 Err(err) => panic!("{err}"),
53 }
54 };
55}
56
57#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
58pub(crate) struct RouteId(u32);
59
60#[must_use]
68pub struct Router<S = ()> {
69 inner: Arc<RouterInner<S>>,
70}
71
72impl<S> Clone for Router<S> {
73 fn clone(&self) -> Self {
74 Self {
75 inner: Arc::clone(&self.inner),
76 }
77 }
78}
79
80struct RouterInner<S> {
81 path_router: PathRouter<S, false>,
82 fallback_router: PathRouter<S, true>,
83 default_fallback: bool,
84 catch_all_fallback: Fallback<S>,
85}
86
87impl<S> Default for Router<S>
88where
89 S: Clone + Send + Sync + 'static,
90{
91 fn default() -> Self {
92 Self::new()
93 }
94}
95
96impl<S> fmt::Debug for Router<S> {
97 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
98 f.debug_struct("Router")
99 .field("path_router", &self.inner.path_router)
100 .field("fallback_router", &self.inner.fallback_router)
101 .field("default_fallback", &self.inner.default_fallback)
102 .field("catch_all_fallback", &self.inner.catch_all_fallback)
103 .finish()
104 }
105}
106
107pub(crate) const NEST_TAIL_PARAM: &str = "__private__axum_nest_tail_param";
108#[cfg(feature = "matched-path")]
109pub(crate) const NEST_TAIL_PARAM_CAPTURE: &str = "/{*__private__axum_nest_tail_param}";
110pub(crate) const FALLBACK_PARAM: &str = "__private__axum_fallback";
111pub(crate) const FALLBACK_PARAM_PATH: &str = "/{*__private__axum_fallback}";
112
113macro_rules! map_inner {
114 ( $self_:ident, $inner:pat_param => $expr:expr) => {
115 #[allow(redundant_semicolons)]
116 {
117 let $inner = $self_.into_inner();
118 Router {
119 inner: Arc::new($expr),
120 }
121 }
122 };
123}
124
125macro_rules! tap_inner {
126 ( $self_:ident, mut $inner:ident => { $($stmt:stmt)* } ) => {
127 #[allow(redundant_semicolons)]
128 {
129 let mut $inner = $self_.into_inner();
130 $($stmt)*;
131 Router {
132 inner: Arc::new($inner),
133 }
134 }
135 };
136}
137
138impl<S> Router<S>
139where
140 S: Clone + Send + Sync + 'static,
141{
142 pub fn new() -> Self {
147 Self {
148 inner: Arc::new(RouterInner {
149 path_router: Default::default(),
150 fallback_router: PathRouter::new_fallback(),
151 default_fallback: true,
152 catch_all_fallback: Fallback::Default(Route::new(NotFound)),
153 }),
154 }
155 }
156
157 fn into_inner(self) -> RouterInner<S> {
158 match Arc::try_unwrap(self.inner) {
159 Ok(inner) => inner,
160 Err(arc) => RouterInner {
161 path_router: arc.path_router.clone(),
162 fallback_router: arc.fallback_router.clone(),
163 default_fallback: arc.default_fallback,
164 catch_all_fallback: arc.catch_all_fallback.clone(),
165 },
166 }
167 }
168
169 #[doc = include_str!("../docs/routing/without_v07_checks.md")]
170 pub fn without_v07_checks(self) -> Self {
171 tap_inner!(self, mut this => {
172 this.path_router.without_v07_checks();
173 })
174 }
175
176 #[doc = include_str!("../docs/routing/route.md")]
177 #[track_caller]
178 pub fn route(self, path: &str, method_router: MethodRouter<S>) -> Self {
179 tap_inner!(self, mut this => {
180 panic_on_err!(this.path_router.route(path, method_router));
181 })
182 }
183
184 #[doc = include_str!("../docs/routing/route_service.md")]
185 pub fn route_service<T>(self, path: &str, service: T) -> Self
186 where
187 T: Service<Request, Error = Infallible> + Clone + Send + Sync + 'static,
188 T::Response: IntoResponse,
189 T::Future: Send + 'static,
190 {
191 let service = match try_downcast::<Router<S>, _>(service) {
192 Ok(_) => {
193 panic!(
194 "Invalid route: `Router::route_service` cannot be used with `Router`s. \
195 Use `Router::nest` instead"
196 );
197 }
198 Err(service) => service,
199 };
200
201 tap_inner!(self, mut this => {
202 panic_on_err!(this.path_router.route_service(path, service));
203 })
204 }
205
206 #[doc = include_str!("../docs/routing/nest.md")]
207 #[doc(alias = "scope")] #[track_caller]
209 pub fn nest(self, path: &str, router: Router<S>) -> Self {
210 if path.is_empty() || path == "/" {
211 panic!("Nesting at the root is no longer supported. Use merge instead.");
212 }
213
214 let RouterInner {
215 path_router,
216 fallback_router,
217 default_fallback,
218 catch_all_fallback: _,
222 } = router.into_inner();
223
224 tap_inner!(self, mut this => {
225 panic_on_err!(this.path_router.nest(path, path_router));
226
227 if !default_fallback {
228 panic_on_err!(this.fallback_router.nest(path, fallback_router));
229 }
230 })
231 }
232
233 #[track_caller]
235 pub fn nest_service<T>(self, path: &str, service: T) -> Self
236 where
237 T: Service<Request, Error = Infallible> + Clone + Send + Sync + 'static,
238 T::Response: IntoResponse,
239 T::Future: Send + 'static,
240 {
241 if path.is_empty() || path == "/" {
242 panic!("Nesting at the root is no longer supported. Use fallback_service instead.");
243 }
244
245 tap_inner!(self, mut this => {
246 panic_on_err!(this.path_router.nest_service(path, service));
247 })
248 }
249
250 #[doc = include_str!("../docs/routing/merge.md")]
251 #[track_caller]
252 pub fn merge<R>(self, other: R) -> Self
253 where
254 R: Into<Router<S>>,
255 {
256 const PANIC_MSG: &str =
257 "Failed to merge fallbacks. This is a bug in axum. Please file an issue";
258
259 let other: Router<S> = other.into();
260 let RouterInner {
261 path_router,
262 fallback_router: mut other_fallback,
263 default_fallback,
264 catch_all_fallback,
265 } = other.into_inner();
266
267 map_inner!(self, mut this => {
268 panic_on_err!(this.path_router.merge(path_router));
269
270 match (this.default_fallback, default_fallback) {
271 (true, true) => {
274 this.fallback_router.merge(other_fallback).expect(PANIC_MSG);
275 }
276 (true, false) => {
278 this.fallback_router.merge(other_fallback).expect(PANIC_MSG);
279 this.default_fallback = false;
280 }
281 (false, true) => {
283 let fallback_router = std::mem::take(&mut this.fallback_router);
284 other_fallback.merge(fallback_router).expect(PANIC_MSG);
285 this.fallback_router = other_fallback;
286 }
287 (false, false) => {
289 panic!("Cannot merge two `Router`s that both have a fallback")
290 }
291 };
292
293 this.catch_all_fallback = this
294 .catch_all_fallback
295 .merge(catch_all_fallback)
296 .unwrap_or_else(|| panic!("Cannot merge two `Router`s that both have a fallback"));
297
298 this
299 })
300 }
301
302 #[doc = include_str!("../docs/routing/layer.md")]
303 pub fn layer<L>(self, layer: L) -> Router<S>
304 where
305 L: Layer<Route> + Clone + Send + Sync + 'static,
306 L::Service: Service<Request> + Clone + Send + Sync + 'static,
307 <L::Service as Service<Request>>::Response: IntoResponse + 'static,
308 <L::Service as Service<Request>>::Error: Into<Infallible> + 'static,
309 <L::Service as Service<Request>>::Future: Send + 'static,
310 {
311 map_inner!(self, this => RouterInner {
312 path_router: this.path_router.layer(layer.clone()),
313 fallback_router: this.fallback_router.layer(layer.clone()),
314 default_fallback: this.default_fallback,
315 catch_all_fallback: this.catch_all_fallback.map(|route| route.layer(layer)),
316 })
317 }
318
319 #[doc = include_str!("../docs/routing/route_layer.md")]
320 #[track_caller]
321 pub fn route_layer<L>(self, layer: L) -> Self
322 where
323 L: Layer<Route> + Clone + Send + Sync + 'static,
324 L::Service: Service<Request> + Clone + Send + Sync + 'static,
325 <L::Service as Service<Request>>::Response: IntoResponse + 'static,
326 <L::Service as Service<Request>>::Error: Into<Infallible> + 'static,
327 <L::Service as Service<Request>>::Future: Send + 'static,
328 {
329 map_inner!(self, this => RouterInner {
330 path_router: this.path_router.route_layer(layer),
331 fallback_router: this.fallback_router,
332 default_fallback: this.default_fallback,
333 catch_all_fallback: this.catch_all_fallback,
334 })
335 }
336
337 pub fn has_routes(&self) -> bool {
339 self.inner.path_router.has_routes()
340 }
341
342 #[track_caller]
343 #[doc = include_str!("../docs/routing/fallback.md")]
344 pub fn fallback<H, T>(self, handler: H) -> Self
345 where
346 H: Handler<T, S>,
347 T: 'static,
348 {
349 tap_inner!(self, mut this => {
350 this.catch_all_fallback =
351 Fallback::BoxedHandler(BoxedIntoRoute::from_handler(handler.clone()));
352 })
353 .fallback_endpoint(Endpoint::MethodRouter(any(handler)))
354 }
355
356 pub fn fallback_service<T>(self, service: T) -> Self
360 where
361 T: Service<Request, Error = Infallible> + Clone + Send + Sync + 'static,
362 T::Response: IntoResponse,
363 T::Future: Send + 'static,
364 {
365 let route = Route::new(service);
366 tap_inner!(self, mut this => {
367 this.catch_all_fallback = Fallback::Service(route.clone());
368 })
369 .fallback_endpoint(Endpoint::Route(route))
370 }
371
372 #[doc = include_str!("../docs/routing/method_not_allowed_fallback.md")]
373 pub fn method_not_allowed_fallback<H, T>(self, handler: H) -> Self
374 where
375 H: Handler<T, S>,
376 T: 'static,
377 {
378 tap_inner!(self, mut this => {
379 this.path_router
380 .method_not_allowed_fallback(handler.clone());
381 })
382 }
383
384 pub fn reset_fallback(self) -> Self {
392 tap_inner!(self, mut this => {
393 this.fallback_router = PathRouter::new_fallback();
394 this.default_fallback = true;
395 this.catch_all_fallback = Fallback::Default(Route::new(NotFound));
396 })
397 }
398
399 fn fallback_endpoint(self, endpoint: Endpoint<S>) -> Self {
400 tap_inner!(self, mut this => {
401 this.fallback_router.set_fallback(endpoint);
402 this.default_fallback = false;
403 })
404 }
405
406 #[doc = include_str!("../docs/routing/with_state.md")]
407 pub fn with_state<S2>(self, state: S) -> Router<S2> {
408 map_inner!(self, this => RouterInner {
409 path_router: this.path_router.with_state(state.clone()),
410 fallback_router: this.fallback_router.with_state(state.clone()),
411 default_fallback: this.default_fallback,
412 catch_all_fallback: this.catch_all_fallback.with_state(state),
413 })
414 }
415
416 pub(crate) fn call_with_state(&self, req: Request, state: S) -> RouteFuture<Infallible> {
417 let (req, state) = match self.inner.path_router.call_with_state(req, state) {
418 Ok(future) => return future,
419 Err((req, state)) => (req, state),
420 };
421
422 let (req, state) = match self.inner.fallback_router.call_with_state(req, state) {
423 Ok(future) => return future,
424 Err((req, state)) => (req, state),
425 };
426
427 self.inner
428 .catch_all_fallback
429 .clone()
430 .call_with_state(req, state)
431 }
432
433 pub fn as_service<B>(&mut self) -> RouterAsService<'_, B, S> {
487 RouterAsService {
488 router: self,
489 _marker: PhantomData,
490 }
491 }
492
493 pub fn into_service<B>(self) -> RouterIntoService<B, S> {
499 RouterIntoService {
500 router: self,
501 _marker: PhantomData,
502 }
503 }
504}
505
506impl Router {
507 pub fn into_make_service(self) -> IntoMakeService<Self> {
526 IntoMakeService::new(self.with_state(()))
529 }
530
531 #[doc = include_str!("../docs/routing/into_make_service_with_connect_info.md")]
532 #[cfg(feature = "tokio")]
533 pub fn into_make_service_with_connect_info<C>(self) -> IntoMakeServiceWithConnectInfo<Self, C> {
534 IntoMakeServiceWithConnectInfo::new(self.with_state(()))
537 }
538}
539
540#[cfg(all(feature = "tokio", any(feature = "http1", feature = "http2")))]
542const _: () = {
543 use crate::serve;
544
545 impl<L> Service<serve::IncomingStream<'_, L>> for Router<()>
546 where
547 L: serve::Listener,
548 {
549 type Response = Self;
550 type Error = Infallible;
551 type Future = std::future::Ready<Result<Self::Response, Self::Error>>;
552
553 fn poll_ready(&mut self, _cx: &mut Context<'_>) -> Poll<Result<(), Self::Error>> {
554 Poll::Ready(Ok(()))
555 }
556
557 fn call(&mut self, _req: serve::IncomingStream<'_, L>) -> Self::Future {
558 std::future::ready(Ok(self.clone().with_state(())))
561 }
562 }
563};
564
565impl<B> Service<Request<B>> for Router<()>
566where
567 B: HttpBody<Data = bytes::Bytes> + Send + 'static,
568 B::Error: Into<axum_core::BoxError>,
569{
570 type Response = Response;
571 type Error = Infallible;
572 type Future = RouteFuture<Infallible>;
573
574 #[inline]
575 fn poll_ready(&mut self, _: &mut Context<'_>) -> Poll<Result<(), Self::Error>> {
576 Poll::Ready(Ok(()))
577 }
578
579 #[inline]
580 fn call(&mut self, req: Request<B>) -> Self::Future {
581 let req = req.map(Body::new);
582 self.call_with_state(req, ())
583 }
584}
585
586pub struct RouterAsService<'a, B, S = ()> {
590 router: &'a mut Router<S>,
591 _marker: PhantomData<B>,
592}
593
594impl<B> Service<Request<B>> for RouterAsService<'_, B, ()>
595where
596 B: HttpBody<Data = bytes::Bytes> + Send + 'static,
597 B::Error: Into<axum_core::BoxError>,
598{
599 type Response = Response;
600 type Error = Infallible;
601 type Future = RouteFuture<Infallible>;
602
603 #[inline]
604 fn poll_ready(&mut self, cx: &mut Context<'_>) -> Poll<Result<(), Self::Error>> {
605 <Router as Service<Request<B>>>::poll_ready(self.router, cx)
606 }
607
608 #[inline]
609 fn call(&mut self, req: Request<B>) -> Self::Future {
610 self.router.call(req)
611 }
612}
613
614impl<B, S> fmt::Debug for RouterAsService<'_, B, S>
615where
616 S: fmt::Debug,
617{
618 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
619 f.debug_struct("RouterAsService")
620 .field("router", &self.router)
621 .finish()
622 }
623}
624
625pub struct RouterIntoService<B, S = ()> {
629 router: Router<S>,
630 _marker: PhantomData<B>,
631}
632
633impl<B, S> Clone for RouterIntoService<B, S>
634where
635 Router<S>: Clone,
636{
637 fn clone(&self) -> Self {
638 Self {
639 router: self.router.clone(),
640 _marker: PhantomData,
641 }
642 }
643}
644
645impl<B> Service<Request<B>> for RouterIntoService<B, ()>
646where
647 B: HttpBody<Data = bytes::Bytes> + Send + 'static,
648 B::Error: Into<axum_core::BoxError>,
649{
650 type Response = Response;
651 type Error = Infallible;
652 type Future = RouteFuture<Infallible>;
653
654 #[inline]
655 fn poll_ready(&mut self, cx: &mut Context<'_>) -> Poll<Result<(), Self::Error>> {
656 <Router as Service<Request<B>>>::poll_ready(&mut self.router, cx)
657 }
658
659 #[inline]
660 fn call(&mut self, req: Request<B>) -> Self::Future {
661 self.router.call(req)
662 }
663}
664
665impl<B, S> fmt::Debug for RouterIntoService<B, S>
666where
667 S: fmt::Debug,
668{
669 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
670 f.debug_struct("RouterIntoService")
671 .field("router", &self.router)
672 .finish()
673 }
674}
675
676enum Fallback<S, E = Infallible> {
677 Default(Route<E>),
678 Service(Route<E>),
679 BoxedHandler(BoxedIntoRoute<S, E>),
680}
681
682impl<S, E> Fallback<S, E>
683where
684 S: Clone,
685{
686 fn merge(self, other: Self) -> Option<Self> {
687 match (self, other) {
688 (Self::Default(_), pick @ Self::Default(_)) => Some(pick),
689 (Self::Default(_), pick) | (pick, Self::Default(_)) => Some(pick),
690 _ => None,
691 }
692 }
693
694 fn map<F, E2>(self, f: F) -> Fallback<S, E2>
695 where
696 S: 'static,
697 E: 'static,
698 F: FnOnce(Route<E>) -> Route<E2> + Clone + Send + Sync + 'static,
699 E2: 'static,
700 {
701 match self {
702 Self::Default(route) => Fallback::Default(f(route)),
703 Self::Service(route) => Fallback::Service(f(route)),
704 Self::BoxedHandler(handler) => Fallback::BoxedHandler(handler.map(f)),
705 }
706 }
707
708 fn with_state<S2>(self, state: S) -> Fallback<S2, E> {
709 match self {
710 Fallback::Default(route) => Fallback::Default(route),
711 Fallback::Service(route) => Fallback::Service(route),
712 Fallback::BoxedHandler(handler) => Fallback::Service(handler.into_route(state)),
713 }
714 }
715
716 fn call_with_state(self, req: Request, state: S) -> RouteFuture<E> {
717 match self {
718 Fallback::Default(route) | Fallback::Service(route) => route.oneshot_inner_owned(req),
719 Fallback::BoxedHandler(handler) => {
720 let route = handler.clone().into_route(state);
721 route.oneshot_inner_owned(req)
722 }
723 }
724 }
725}
726
727impl<S, E> Clone for Fallback<S, E> {
728 fn clone(&self) -> Self {
729 match self {
730 Self::Default(inner) => Self::Default(inner.clone()),
731 Self::Service(inner) => Self::Service(inner.clone()),
732 Self::BoxedHandler(inner) => Self::BoxedHandler(inner.clone()),
733 }
734 }
735}
736
737impl<S, E> fmt::Debug for Fallback<S, E> {
738 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
739 match self {
740 Self::Default(inner) => f.debug_tuple("Default").field(inner).finish(),
741 Self::Service(inner) => f.debug_tuple("Service").field(inner).finish(),
742 Self::BoxedHandler(_) => f.debug_tuple("BoxedHandler").finish(),
743 }
744 }
745}
746
747#[allow(clippy::large_enum_variant)]
748enum Endpoint<S> {
749 MethodRouter(MethodRouter<S>),
750 Route(Route),
751}
752
753impl<S> Endpoint<S>
754where
755 S: Clone + Send + Sync + 'static,
756{
757 fn layer<L>(self, layer: L) -> Endpoint<S>
758 where
759 L: Layer<Route> + Clone + Send + Sync + 'static,
760 L::Service: Service<Request> + Clone + Send + Sync + 'static,
761 <L::Service as Service<Request>>::Response: IntoResponse + 'static,
762 <L::Service as Service<Request>>::Error: Into<Infallible> + 'static,
763 <L::Service as Service<Request>>::Future: Send + 'static,
764 {
765 match self {
766 Endpoint::MethodRouter(method_router) => {
767 Endpoint::MethodRouter(method_router.layer(layer))
768 }
769 Endpoint::Route(route) => Endpoint::Route(route.layer(layer)),
770 }
771 }
772}
773
774impl<S> Clone for Endpoint<S> {
775 fn clone(&self) -> Self {
776 match self {
777 Self::MethodRouter(inner) => Self::MethodRouter(inner.clone()),
778 Self::Route(inner) => Self::Route(inner.clone()),
779 }
780 }
781}
782
783impl<S> fmt::Debug for Endpoint<S> {
784 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
785 match self {
786 Self::MethodRouter(method_router) => {
787 f.debug_tuple("MethodRouter").field(method_router).finish()
788 }
789 Self::Route(route) => f.debug_tuple("Route").field(route).finish(),
790 }
791 }
792}
793
794#[test]
795fn traits() {
796 use crate::test_helpers::*;
797 assert_send::<Router<()>>();
798 assert_sync::<Router<()>>();
799}