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 fn fallback_endpoint(self, endpoint: Endpoint<S>) -> Self {
385 tap_inner!(self, mut this => {
386 this.fallback_router.set_fallback(endpoint);
387 this.default_fallback = false;
388 })
389 }
390
391 #[doc = include_str!("../docs/routing/with_state.md")]
392 pub fn with_state<S2>(self, state: S) -> Router<S2> {
393 map_inner!(self, this => RouterInner {
394 path_router: this.path_router.with_state(state.clone()),
395 fallback_router: this.fallback_router.with_state(state.clone()),
396 default_fallback: this.default_fallback,
397 catch_all_fallback: this.catch_all_fallback.with_state(state),
398 })
399 }
400
401 pub(crate) fn call_with_state(&self, req: Request, state: S) -> RouteFuture<Infallible> {
402 let (req, state) = match self.inner.path_router.call_with_state(req, state) {
403 Ok(future) => return future,
404 Err((req, state)) => (req, state),
405 };
406
407 let (req, state) = match self.inner.fallback_router.call_with_state(req, state) {
408 Ok(future) => return future,
409 Err((req, state)) => (req, state),
410 };
411
412 self.inner
413 .catch_all_fallback
414 .clone()
415 .call_with_state(req, state)
416 }
417
418 pub fn as_service<B>(&mut self) -> RouterAsService<'_, B, S> {
472 RouterAsService {
473 router: self,
474 _marker: PhantomData,
475 }
476 }
477
478 pub fn into_service<B>(self) -> RouterIntoService<B, S> {
484 RouterIntoService {
485 router: self,
486 _marker: PhantomData,
487 }
488 }
489}
490
491impl Router {
492 pub fn into_make_service(self) -> IntoMakeService<Self> {
511 IntoMakeService::new(self.with_state(()))
514 }
515
516 #[doc = include_str!("../docs/routing/into_make_service_with_connect_info.md")]
517 #[cfg(feature = "tokio")]
518 pub fn into_make_service_with_connect_info<C>(self) -> IntoMakeServiceWithConnectInfo<Self, C> {
519 IntoMakeServiceWithConnectInfo::new(self.with_state(()))
522 }
523}
524
525#[cfg(all(feature = "tokio", any(feature = "http1", feature = "http2")))]
527const _: () = {
528 use crate::serve;
529
530 impl<L> Service<serve::IncomingStream<'_, L>> for Router<()>
531 where
532 L: serve::Listener,
533 {
534 type Response = Self;
535 type Error = Infallible;
536 type Future = std::future::Ready<Result<Self::Response, Self::Error>>;
537
538 fn poll_ready(&mut self, _cx: &mut Context<'_>) -> Poll<Result<(), Self::Error>> {
539 Poll::Ready(Ok(()))
540 }
541
542 fn call(&mut self, _req: serve::IncomingStream<'_, L>) -> Self::Future {
543 std::future::ready(Ok(self.clone().with_state(())))
546 }
547 }
548};
549
550impl<B> Service<Request<B>> for Router<()>
551where
552 B: HttpBody<Data = bytes::Bytes> + Send + 'static,
553 B::Error: Into<axum_core::BoxError>,
554{
555 type Response = Response;
556 type Error = Infallible;
557 type Future = RouteFuture<Infallible>;
558
559 #[inline]
560 fn poll_ready(&mut self, _: &mut Context<'_>) -> Poll<Result<(), Self::Error>> {
561 Poll::Ready(Ok(()))
562 }
563
564 #[inline]
565 fn call(&mut self, req: Request<B>) -> Self::Future {
566 let req = req.map(Body::new);
567 self.call_with_state(req, ())
568 }
569}
570
571pub struct RouterAsService<'a, B, S = ()> {
575 router: &'a mut Router<S>,
576 _marker: PhantomData<B>,
577}
578
579impl<B> Service<Request<B>> for RouterAsService<'_, B, ()>
580where
581 B: HttpBody<Data = bytes::Bytes> + Send + 'static,
582 B::Error: Into<axum_core::BoxError>,
583{
584 type Response = Response;
585 type Error = Infallible;
586 type Future = RouteFuture<Infallible>;
587
588 #[inline]
589 fn poll_ready(&mut self, cx: &mut Context<'_>) -> Poll<Result<(), Self::Error>> {
590 <Router as Service<Request<B>>>::poll_ready(self.router, cx)
591 }
592
593 #[inline]
594 fn call(&mut self, req: Request<B>) -> Self::Future {
595 self.router.call(req)
596 }
597}
598
599impl<B, S> fmt::Debug for RouterAsService<'_, B, S>
600where
601 S: fmt::Debug,
602{
603 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
604 f.debug_struct("RouterAsService")
605 .field("router", &self.router)
606 .finish()
607 }
608}
609
610pub struct RouterIntoService<B, S = ()> {
614 router: Router<S>,
615 _marker: PhantomData<B>,
616}
617
618impl<B, S> Clone for RouterIntoService<B, S>
619where
620 Router<S>: Clone,
621{
622 fn clone(&self) -> Self {
623 Self {
624 router: self.router.clone(),
625 _marker: PhantomData,
626 }
627 }
628}
629
630impl<B> Service<Request<B>> for RouterIntoService<B, ()>
631where
632 B: HttpBody<Data = bytes::Bytes> + Send + 'static,
633 B::Error: Into<axum_core::BoxError>,
634{
635 type Response = Response;
636 type Error = Infallible;
637 type Future = RouteFuture<Infallible>;
638
639 #[inline]
640 fn poll_ready(&mut self, cx: &mut Context<'_>) -> Poll<Result<(), Self::Error>> {
641 <Router as Service<Request<B>>>::poll_ready(&mut self.router, cx)
642 }
643
644 #[inline]
645 fn call(&mut self, req: Request<B>) -> Self::Future {
646 self.router.call(req)
647 }
648}
649
650impl<B, S> fmt::Debug for RouterIntoService<B, S>
651where
652 S: fmt::Debug,
653{
654 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
655 f.debug_struct("RouterIntoService")
656 .field("router", &self.router)
657 .finish()
658 }
659}
660
661enum Fallback<S, E = Infallible> {
662 Default(Route<E>),
663 Service(Route<E>),
664 BoxedHandler(BoxedIntoRoute<S, E>),
665}
666
667impl<S, E> Fallback<S, E>
668where
669 S: Clone,
670{
671 fn merge(self, other: Self) -> Option<Self> {
672 match (self, other) {
673 (Self::Default(_), pick @ Self::Default(_)) => Some(pick),
674 (Self::Default(_), pick) | (pick, Self::Default(_)) => Some(pick),
675 _ => None,
676 }
677 }
678
679 fn map<F, E2>(self, f: F) -> Fallback<S, E2>
680 where
681 S: 'static,
682 E: 'static,
683 F: FnOnce(Route<E>) -> Route<E2> + Clone + Send + Sync + 'static,
684 E2: 'static,
685 {
686 match self {
687 Self::Default(route) => Fallback::Default(f(route)),
688 Self::Service(route) => Fallback::Service(f(route)),
689 Self::BoxedHandler(handler) => Fallback::BoxedHandler(handler.map(f)),
690 }
691 }
692
693 fn with_state<S2>(self, state: S) -> Fallback<S2, E> {
694 match self {
695 Fallback::Default(route) => Fallback::Default(route),
696 Fallback::Service(route) => Fallback::Service(route),
697 Fallback::BoxedHandler(handler) => Fallback::Service(handler.into_route(state)),
698 }
699 }
700
701 fn call_with_state(self, req: Request, state: S) -> RouteFuture<E> {
702 match self {
703 Fallback::Default(route) | Fallback::Service(route) => route.oneshot_inner_owned(req),
704 Fallback::BoxedHandler(handler) => {
705 let route = handler.clone().into_route(state);
706 route.oneshot_inner_owned(req)
707 }
708 }
709 }
710}
711
712impl<S, E> Clone for Fallback<S, E> {
713 fn clone(&self) -> Self {
714 match self {
715 Self::Default(inner) => Self::Default(inner.clone()),
716 Self::Service(inner) => Self::Service(inner.clone()),
717 Self::BoxedHandler(inner) => Self::BoxedHandler(inner.clone()),
718 }
719 }
720}
721
722impl<S, E> fmt::Debug for Fallback<S, E> {
723 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
724 match self {
725 Self::Default(inner) => f.debug_tuple("Default").field(inner).finish(),
726 Self::Service(inner) => f.debug_tuple("Service").field(inner).finish(),
727 Self::BoxedHandler(_) => f.debug_tuple("BoxedHandler").finish(),
728 }
729 }
730}
731
732#[allow(clippy::large_enum_variant)]
733enum Endpoint<S> {
734 MethodRouter(MethodRouter<S>),
735 Route(Route),
736}
737
738impl<S> Endpoint<S>
739where
740 S: Clone + Send + Sync + 'static,
741{
742 fn layer<L>(self, layer: L) -> Endpoint<S>
743 where
744 L: Layer<Route> + Clone + Send + Sync + 'static,
745 L::Service: Service<Request> + Clone + Send + Sync + 'static,
746 <L::Service as Service<Request>>::Response: IntoResponse + 'static,
747 <L::Service as Service<Request>>::Error: Into<Infallible> + 'static,
748 <L::Service as Service<Request>>::Future: Send + 'static,
749 {
750 match self {
751 Endpoint::MethodRouter(method_router) => {
752 Endpoint::MethodRouter(method_router.layer(layer))
753 }
754 Endpoint::Route(route) => Endpoint::Route(route.layer(layer)),
755 }
756 }
757}
758
759impl<S> Clone for Endpoint<S> {
760 fn clone(&self) -> Self {
761 match self {
762 Self::MethodRouter(inner) => Self::MethodRouter(inner.clone()),
763 Self::Route(inner) => Self::Route(inner.clone()),
764 }
765 }
766}
767
768impl<S> fmt::Debug for Endpoint<S> {
769 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
770 match self {
771 Self::MethodRouter(method_router) => {
772 f.debug_tuple("MethodRouter").field(method_router).finish()
773 }
774 Self::Route(route) => f.debug_tuple("Route").field(route).finish(),
775 }
776 }
777}
778
779#[test]
780fn traits() {
781 use crate::test_helpers::*;
782 assert_send::<Router<()>>();
783 assert_sync::<Router<()>>();
784}