From a0af61ea46467a3513050dd007bba2e7f53057db Mon Sep 17 00:00:00 2001 From: David Pedersen Date: Wed, 22 Mar 2023 11:48:23 +0100 Subject: [PATCH] More clearly document what wildcards matches (#1873) --- axum/src/docs/routing/route.md | 5 +++++ axum/src/routing/tests/mod.rs | 28 ++++++++++++++++++++++++++++ 2 files changed, 33 insertions(+) diff --git a/axum/src/docs/routing/route.md b/axum/src/docs/routing/route.md index fcc68cc4..ae425142 100644 --- a/axum/src/docs/routing/route.md +++ b/axum/src/docs/routing/route.md @@ -50,6 +50,11 @@ Examples: - `/assets/*path` - `/:id/:repo/*tree` +Note that `/*key` doesn't match empty segments. Thus: + +- `/*key` doesn't match `/` but does match `/a`, `/a/`, etc. +- `/x/*key` doesn't match `/x` or `/x/` but does match `/x/a`, `/x/a/`, etc. + Wildcard captures can also be extracted using [`Path`](crate::extract::Path). Note that the leading slash is not included, i.e. for the route `/foo/*rest` and the path `/foo/bar/baz` the value of `rest` will be `bar/baz`. diff --git a/axum/src/routing/tests/mod.rs b/axum/src/routing/tests/mod.rs index 70fccaf0..bed48415 100644 --- a/axum/src/routing/tests/mod.rs +++ b/axum/src/routing/tests/mod.rs @@ -380,6 +380,34 @@ async fn wildcard_doesnt_match_just_trailing_slash() { assert_eq!(res.text().await, "foo/bar"); } +#[crate::test] +async fn what_matches_wildcard() { + let app = Router::new() + .route("/*key", get(|| async { "root" })) + .route("/x/*key", get(|| async { "x" })) + .fallback(|| async { "fallback" }); + + let client = TestClient::new(app); + + let get = |path| { + let f = client.get(path).send(); + async move { f.await.text().await } + }; + + assert_eq!(get("/").await, "fallback"); + assert_eq!(get("/a").await, "root"); + assert_eq!(get("/a/").await, "root"); + assert_eq!(get("/a/b").await, "root"); + assert_eq!(get("/a/b/").await, "root"); + + assert_eq!(get("/x").await, "root"); + assert_eq!(get("/x/").await, "root"); + assert_eq!(get("/x/a").await, "x"); + assert_eq!(get("/x/a/").await, "x"); + assert_eq!(get("/x/a/b").await, "x"); + assert_eq!(get("/x/a/b/").await, "x"); +} + #[crate::test] async fn static_and_dynamic_paths() { let app = Router::new()