diff --git a/axum/CHANGELOG.md b/axum/CHANGELOG.md index 14b52f1f..13730f5b 100644 --- a/axum/CHANGELOG.md +++ b/axum/CHANGELOG.md @@ -9,8 +9,10 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 - **change:** Avoid cloning `Arc` during deserialization of `Path` - **added:** `axum::serve::Serve::tcp_nodelay` and `axum::serve::WithGracefulShutdown::tcp_nodelay` ([#2653]) +- **added:** `Router::has_routes` function ([#2790]) [#2653]: https://github.com/tokio-rs/axum/pull/2653 +[#2790]: https://github.com/tokio-rs/axum/pull/2790 # 0.7.5 (24. March, 2024) diff --git a/axum/src/docs/routing/route_layer.md b/axum/src/docs/routing/route_layer.md index bc7b2197..9cce3ea7 100644 --- a/axum/src/docs/routing/route_layer.md +++ b/axum/src/docs/routing/route_layer.md @@ -11,6 +11,10 @@ the request matches a route. This is useful for middleware that return early (such as authorization) which might otherwise convert a `404 Not Found` into a `401 Unauthorized`. +This function will panic if no routes have been declared yet on the router, +since the new layer will have no effect, and this is typically a bug. +In generic code, you can test if that is the case first, by calling [`Router::has_routes`]. + # Example ```rust diff --git a/axum/src/routing/mod.rs b/axum/src/routing/mod.rs index 47b85474..dc6ca815 100644 --- a/axum/src/routing/mod.rs +++ b/axum/src/routing/mod.rs @@ -307,6 +307,11 @@ where }) } + /// True if the router currently has at least one route added. + pub fn has_routes(&self) -> bool { + self.inner.path_router.has_routes() + } + #[track_caller] #[doc = include_str!("../docs/routing/fallback.md")] pub fn fallback(self, handler: H) -> Self diff --git a/axum/src/routing/path_router.rs b/axum/src/routing/path_router.rs index 345d6671..e132f1dc 100644 --- a/axum/src/routing/path_router.rs +++ b/axum/src/routing/path_router.rs @@ -290,6 +290,10 @@ where } } + pub(super) fn has_routes(&self) -> bool { + !self.routes.is_empty() + } + pub(super) fn with_state(self, state: S) -> PathRouter { let routes = self .routes