Skip to content

Commit 1143694

Browse files
erin-desumladedav
andauthored
Fix TSR redirecting to top-level inside nested Router (#2993)
Co-authored-by: David Mládek <[email protected]>
1 parent 65ad603 commit 1143694

File tree

2 files changed

+19
-3
lines changed

2 files changed

+19
-3
lines changed

axum-extra/Cargo.toml

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -39,7 +39,7 @@ typed-header = ["dep:headers"]
3939
typed-routing = ["dep:axum-macros", "dep:percent-encoding", "dep:serde_html_form", "dep:form_urlencoded"]
4040

4141
[dependencies]
42-
axum = { path = "../axum", version = "0.8.0-alpha.1", default-features = false }
42+
axum = { path = "../axum", version = "0.8.0-alpha.1", default-features = false, features = ["original-uri"] }
4343
axum-core = { path = "../axum-core", version = "0.5.0-alpha.1" }
4444
bytes = "1.1.0"
4545
futures-util = { version = "0.3", default-features = false, features = ["alloc"] }

axum-extra/src/routing/mod.rs

Lines changed: 18 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,7 @@
11
//! Additional types for defining routes.
22
33
use axum::{
4-
extract::Request,
4+
extract::{OriginalUri, Request},
55
response::{IntoResponse, Redirect, Response},
66
routing::{any, MethodRouter},
77
Router,
@@ -313,7 +313,7 @@ fn add_tsr_redirect_route<S>(router: Router<S>, path: &str) -> Router<S>
313313
where
314314
S: Clone + Send + Sync + 'static,
315315
{
316-
async fn redirect_handler(uri: Uri) -> Response {
316+
async fn redirect_handler(OriginalUri(uri): OriginalUri) -> Response {
317317
let new_uri = map_path(uri, |path| {
318318
path.strip_suffix('/')
319319
.map(Cow::Borrowed)
@@ -432,6 +432,22 @@ mod tests {
432432
assert_eq!(res.headers()["location"], "/foo?a=a");
433433
}
434434

435+
#[tokio::test]
436+
async fn tsr_works_in_nested_router() {
437+
let app = Router::new().nest(
438+
"/neko",
439+
Router::new().route_with_tsr("/nyan/", get(|| async {})),
440+
);
441+
442+
let client = TestClient::new(app);
443+
let res = client.get("/neko/nyan/").await;
444+
assert_eq!(res.status(), StatusCode::OK);
445+
446+
let res = client.get("/neko/nyan").await;
447+
assert_eq!(res.status(), StatusCode::PERMANENT_REDIRECT);
448+
assert_eq!(res.headers()["location"], "/neko/nyan/");
449+
}
450+
435451
#[test]
436452
#[should_panic = "Cannot add a trailing slash redirect route for `/`"]
437453
fn tsr_at_root() {

0 commit comments

Comments
 (0)