Add Router::has_routes (#2790)

This commit is contained in:
Chris Beck 2024-06-22 15:31:22 -06:00 committed by GitHub
parent 670bf694dc
commit 4f3999c20f
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
4 changed files with 15 additions and 0 deletions

View file

@ -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` - **change:** Avoid cloning `Arc` during deserialization of `Path`
- **added:** `axum::serve::Serve::tcp_nodelay` and `axum::serve::WithGracefulShutdown::tcp_nodelay` ([#2653]) - **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 [#2653]: https://github.com/tokio-rs/axum/pull/2653
[#2790]: https://github.com/tokio-rs/axum/pull/2790
# 0.7.5 (24. March, 2024) # 0.7.5 (24. March, 2024)

View file

@ -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 (such as authorization) which might otherwise convert a `404 Not Found` into a
`401 Unauthorized`. `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 # Example
```rust ```rust

View file

@ -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] #[track_caller]
#[doc = include_str!("../docs/routing/fallback.md")] #[doc = include_str!("../docs/routing/fallback.md")]
pub fn fallback<H, T>(self, handler: H) -> Self pub fn fallback<H, T>(self, handler: H) -> Self

View file

@ -290,6 +290,10 @@ where
} }
} }
pub(super) fn has_routes(&self) -> bool {
!self.routes.is_empty()
}
pub(super) fn with_state<S2>(self, state: S) -> PathRouter<S2, IS_FALLBACK> { pub(super) fn with_state<S2>(self, state: S) -> PathRouter<S2, IS_FALLBACK> {
let routes = self let routes = self
.routes .routes