Panic when attempting to add a route_layer to an empty router (#1327)

This commit is contained in:
Jonas Platte 2022-08-25 15:42:17 +02:00 committed by GitHub
parent 426b9f91e8
commit 92f6b68390
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
3 changed files with 31 additions and 1 deletions

View file

@ -7,7 +7,13 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
# Unreleased
- None
## Routing
- **breaking:** Adding a `.route_layer` onto a `Router` or `MethodRouter`
without any routes will now result in a panic. Previously, this just did
nothing. [#1327]
[#1327]: https://github.com/tokio-rs/axum/pull/1327
# 0.6.0-rc.1 (23. August, 2022)

View file

@ -852,6 +852,7 @@ where
}
#[doc = include_str!("../docs/method_routing/route_layer.md")]
#[track_caller]
pub fn route_layer<L>(mut self, layer: L) -> MethodRouter<S, B, E>
where
L: Layer<Route<B, E>>,
@ -859,6 +860,21 @@ where
<L::Service as Service<Request<B>>>::Response: IntoResponse + 'static,
<L::Service as Service<Request<B>>>::Future: Send + 'static,
{
if self.get.is_none()
&& self.head.is_none()
&& self.delete.is_none()
&& self.options.is_none()
&& self.patch.is_none()
&& self.post.is_none()
&& self.put.is_none()
&& self.trace.is_none()
{
panic!(
"Adding a route_layer before any routes is a no-op. \
Add the routes you want the layer to apply to first."
);
}
let layer_fn = |svc| {
let svc = layer.layer(svc);
let svc = MapResponseLayer::new(IntoResponse::into_response).layer(svc);

View file

@ -352,6 +352,7 @@ where
}
#[doc = include_str!("../docs/routing/route_layer.md")]
#[track_caller]
pub fn route_layer<L>(self, layer: L) -> Self
where
L: Layer<Route<B>>,
@ -360,6 +361,13 @@ where
<L::Service as Service<Request<B>>>::Error: Into<Infallible> + 'static,
<L::Service as Service<Request<B>>>::Future: Send + 'static,
{
if self.routes.is_empty() {
panic!(
"Adding a route_layer before any routes is a no-op. \
Add the routes you want the layer to apply to first."
);
}
let layer = ServiceBuilder::new()
.map_err(Into::into)
.layer(MapResponseLayer::new(IntoResponse::into_response))