Skip to content

Fix fallback handlers on nested routers returning 404 #2524

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion axum/CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0

# Unreleased

- None.
- **fixed:** Fallback handlers on nested routers returning 404

# 0.7.4 (13. January, 2024)

Expand Down
13 changes: 12 additions & 1 deletion axum/src/routing/path_router.rs
Original file line number Diff line number Diff line change
Expand Up @@ -180,16 +180,27 @@ where
.expect("no path for route id. This is a bug in axum. Please file an issue");

let path = path_for_nested_route(prefix, inner_path);

let route_nested_root =
IS_FALLBACK && "/".eq(inner_path.as_ref()) && !path.ends_with('/');
let nested_root = match route_nested_root {
true => Some(format!("{path}/")),
false => None,
};
let layer = (
StripPrefix::layer(prefix),
SetNestedPath::layer(path_to_nest_at),
);
match endpoint.layer(layer) {
Endpoint::MethodRouter(method_router) => {
if let Some(nested_root) = nested_root {
self.route(&nested_root, method_router.clone())?;
}
self.route(&path, method_router)?;
}
Endpoint::Route(route) => {
if let Some(nested_root) = nested_root {
self.route_endpoint(&nested_root, Endpoint::Route(route.clone()))?;
}
self.route_endpoint(&path, Endpoint::Route(route))?;
}
}
Expand Down
13 changes: 13 additions & 0 deletions axum/src/routing/tests/nest.rs
Original file line number Diff line number Diff line change
Expand Up @@ -383,6 +383,19 @@ async fn nesting_with_root_inner_router() {
assert_eq!(res.status(), StatusCode::OK);
}

#[tokio::test]
async fn nesting_with_root_inner_fallback() {
let app = Router::new().nest("/router", Router::new().fallback(get(|| async {})));

let client = TestClient::new(app);

let res = client.get("/router").await;
assert_eq!(res.status(), StatusCode::OK);

let res = client.get("/router/").await;
assert_eq!(res.status(), StatusCode::OK);
}

macro_rules! nested_route_test {
(
$name:ident,
Expand Down