1use super::{rejection::*, FromRequestParts};
2use crate::routing::{RouteId, NEST_TAIL_PARAM_CAPTURE};
3use axum_core::extract::OptionalFromRequestParts;
4use http::request::Parts;
5use std::{collections::HashMap, convert::Infallible, sync::Arc};
6
7#[cfg_attr(docsrs, doc(cfg(feature = "matched-path")))]
56#[derive(Clone, Debug)]
57pub struct MatchedPath(pub(crate) Arc<str>);
58
59impl MatchedPath {
60 #[must_use]
62 pub fn as_str(&self) -> &str {
63 &self.0
64 }
65}
66
67impl<S> FromRequestParts<S> for MatchedPath
68where
69 S: Send + Sync,
70{
71 type Rejection = MatchedPathRejection;
72
73 async fn from_request_parts(parts: &mut Parts, _state: &S) -> Result<Self, Self::Rejection> {
74 let matched_path = parts
75 .extensions
76 .get::<Self>()
77 .ok_or(MatchedPathRejection::MatchedPathMissing(MatchedPathMissing))?
78 .clone();
79
80 Ok(matched_path)
81 }
82}
83
84impl<S> OptionalFromRequestParts<S> for MatchedPath
85where
86 S: Send + Sync,
87{
88 type Rejection = Infallible;
89
90 async fn from_request_parts(
91 parts: &mut Parts,
92 _state: &S,
93 ) -> Result<Option<Self>, Self::Rejection> {
94 Ok(parts.extensions.get::<Self>().cloned())
95 }
96}
97
98#[derive(Clone, Debug)]
99struct MatchedNestedPath(Arc<str>);
100
101pub(crate) fn set_matched_path_for_request(
102 id: RouteId,
103 route_id_to_path: &HashMap<RouteId, Arc<str>>,
104 extensions: &mut http::Extensions,
105) {
106 let Some(matched_path) = route_id_to_path.get(&id) else {
107 #[cfg(debug_assertions)]
108 panic!("should always have a matched path for a route id");
109 #[cfg(not(debug_assertions))]
110 return;
111 };
112
113 let matched_path = append_nested_matched_path(matched_path, extensions);
114
115 if matched_path.ends_with(NEST_TAIL_PARAM_CAPTURE) {
116 extensions.insert(MatchedNestedPath(matched_path));
117 debug_assert!(extensions.remove::<MatchedPath>().is_none());
118 } else {
119 extensions.insert(MatchedPath(matched_path));
120 extensions.remove::<MatchedNestedPath>();
121 }
122}
123
124fn append_nested_matched_path(matched_path: &Arc<str>, extensions: &http::Extensions) -> Arc<str> {
126 if let Some(previous) = extensions
127 .get::<MatchedPath>()
128 .map(|matched_path| matched_path.as_str())
129 .or_else(|| Some(&extensions.get::<MatchedNestedPath>()?.0))
130 {
131 let previous = previous
132 .strip_suffix(NEST_TAIL_PARAM_CAPTURE)
133 .unwrap_or(previous);
134
135 let matched_path = format!("{previous}{matched_path}");
136 matched_path.into()
137 } else {
138 Arc::clone(matched_path)
139 }
140}
141
142#[cfg(test)]
143mod tests {
144 use super::*;
145 use crate::{
146 extract::Request,
147 handler::HandlerWithoutStateExt,
148 middleware::map_request,
149 routing::{any, get},
150 test_helpers::*,
151 Router,
152 };
153 use http::StatusCode;
154
155 #[crate::test]
156 async fn extracting_on_handler() {
157 let app = Router::new().route(
158 "/{a}",
159 get(|path: MatchedPath| async move { path.as_str().to_owned() }),
160 );
161
162 let client = TestClient::new(app);
163
164 let res = client.get("/foo").await;
165 assert_eq!(res.text().await, "/{a}");
166 }
167
168 #[crate::test]
169 async fn extracting_on_handler_in_nested_router() {
170 let app = Router::new().nest(
171 "/{a}",
172 Router::new().route(
173 "/{b}",
174 get(|path: MatchedPath| async move { path.as_str().to_owned() }),
175 ),
176 );
177
178 let client = TestClient::new(app);
179
180 let res = client.get("/foo/bar").await;
181 assert_eq!(res.text().await, "/{a}/{b}");
182 }
183
184 #[crate::test]
185 async fn extracting_on_handler_in_deeply_nested_router() {
186 let app = Router::new().nest(
187 "/{a}",
188 Router::new().nest(
189 "/{b}",
190 Router::new().route(
191 "/{c}",
192 get(|path: MatchedPath| async move { path.as_str().to_owned() }),
193 ),
194 ),
195 );
196
197 let client = TestClient::new(app);
198
199 let res = client.get("/foo/bar/baz").await;
200 assert_eq!(res.text().await, "/{a}/{b}/{c}");
201 }
202
203 #[crate::test]
204 async fn cannot_extract_nested_matched_path_in_middleware() {
205 async fn extract_matched_path<B>(
206 matched_path: Option<MatchedPath>,
207 req: Request<B>,
208 ) -> Request<B> {
209 assert!(matched_path.is_none());
210 req
211 }
212
213 let app = Router::new()
214 .nest_service("/{a}", Router::new().route("/{b}", get(|| async move {})))
215 .layer(map_request(extract_matched_path));
216
217 let client = TestClient::new(app);
218
219 let res = client.get("/foo/bar").await;
220 assert_eq!(res.status(), StatusCode::OK);
221 }
222
223 #[crate::test]
224 async fn can_extract_nested_matched_path_in_middleware_using_nest() {
225 async fn extract_matched_path<B>(
226 matched_path: Option<MatchedPath>,
227 req: Request<B>,
228 ) -> Request<B> {
229 assert_eq!(matched_path.unwrap().as_str(), "/{a}/{b}");
230 req
231 }
232
233 let app = Router::new()
234 .nest("/{a}", Router::new().route("/{b}", get(|| async move {})))
235 .layer(map_request(extract_matched_path));
236
237 let client = TestClient::new(app);
238
239 let res = client.get("/foo/bar").await;
240 assert_eq!(res.status(), StatusCode::OK);
241 }
242
243 #[crate::test]
244 async fn cannot_extract_nested_matched_path_in_middleware_via_extension() {
245 async fn assert_no_matched_path<B>(req: Request<B>) -> Request<B> {
246 assert!(req.extensions().get::<MatchedPath>().is_none());
247 req
248 }
249
250 let app = Router::new()
251 .nest_service("/{a}", Router::new().route("/{b}", get(|| async move {})))
252 .layer(map_request(assert_no_matched_path));
253
254 let client = TestClient::new(app);
255
256 let res = client.get("/foo/bar").await;
257 assert_eq!(res.status(), StatusCode::OK);
258 }
259
260 #[tokio::test]
261 async fn can_extract_nested_matched_path_in_middleware_via_extension_using_nest() {
262 async fn assert_matched_path<B>(req: Request<B>) -> Request<B> {
263 assert!(req.extensions().get::<MatchedPath>().is_some());
264 req
265 }
266
267 let app = Router::new()
268 .nest("/{a}", Router::new().route("/{b}", get(|| async move {})))
269 .layer(map_request(assert_matched_path));
270
271 let client = TestClient::new(app);
272
273 let res = client.get("/foo/bar").await;
274 assert_eq!(res.status(), StatusCode::OK);
275 }
276
277 #[crate::test]
278 async fn can_extract_nested_matched_path_in_middleware_on_nested_router() {
279 async fn extract_matched_path<B>(matched_path: MatchedPath, req: Request<B>) -> Request<B> {
280 assert_eq!(matched_path.as_str(), "/{a}/{b}");
281 req
282 }
283
284 let app = Router::new().nest(
285 "/{a}",
286 Router::new()
287 .route("/{b}", get(|| async move {}))
288 .layer(map_request(extract_matched_path)),
289 );
290
291 let client = TestClient::new(app);
292
293 let res = client.get("/foo/bar").await;
294 assert_eq!(res.status(), StatusCode::OK);
295 }
296
297 #[crate::test]
298 async fn can_extract_nested_matched_path_with_prefix_in_middleware_on_nested_router() {
299 async fn extract_matched_path<B>(matched_path: MatchedPath, req: Request<B>) -> Request<B> {
300 assert_eq!(matched_path.as_str(), "/foo{one}/bar{two}");
301 req
302 }
303
304 let app = Router::new().nest(
305 "/foo{one}",
306 Router::new()
307 .route("/bar{two}", get(|| async move {}))
308 .layer(map_request(extract_matched_path)),
309 );
310
311 let client = TestClient::new(app);
312
313 let res = client.get("/foo1/bar2").await;
314 assert_eq!(res.status(), StatusCode::OK);
315 }
316
317 #[crate::test]
318 async fn can_extract_nested_matched_path_with_prefix_and_suffix_in_middleware_on_nested_router()
319 {
320 async fn extract_matched_path<B>(matched_path: MatchedPath, req: Request<B>) -> Request<B> {
321 assert_eq!(matched_path.as_str(), "/foo{one}foo/bar{two}bar");
322 req
323 }
324
325 let app = Router::new().nest(
326 "/foo{one}foo",
327 Router::new()
328 .route("/bar{two}bar", get(|| async move {}))
329 .layer(map_request(extract_matched_path)),
330 );
331
332 let client = TestClient::new(app);
333
334 let res = client.get("/foo1foo/bar2bar").await;
335 assert_eq!(res.status(), StatusCode::OK);
336 }
337
338 #[crate::test]
339 async fn can_extract_nested_matched_path_in_middleware_on_nested_router_via_extension() {
340 async fn extract_matched_path<B>(req: Request<B>) -> Request<B> {
341 let matched_path = req.extensions().get::<MatchedPath>().unwrap();
342 assert_eq!(matched_path.as_str(), "/{a}/{b}");
343 req
344 }
345
346 let app = Router::new().nest(
347 "/{a}",
348 Router::new()
349 .route("/{b}", get(|| async move {}))
350 .layer(map_request(extract_matched_path)),
351 );
352
353 let client = TestClient::new(app);
354
355 let res = client.get("/foo/bar").await;
356 assert_eq!(res.status(), StatusCode::OK);
357 }
358
359 #[crate::test]
360 async fn extracting_on_nested_handler() {
361 async fn handler(path: Option<MatchedPath>) {
362 assert!(path.is_none());
363 }
364
365 let app = Router::new().nest_service("/{a}", handler.into_service());
366
367 let client = TestClient::new(app);
368
369 let res = client.get("/foo/bar").await;
370 assert_eq!(res.status(), StatusCode::OK);
371 }
372
373 #[crate::test]
375 async fn doesnt_panic_if_router_called_from_wildcard_route() {
376 use tower::ServiceExt;
377
378 let app = Router::new().route(
379 "/{*path}",
380 any(|req: Request| {
381 Router::new()
382 .nest("/foo", Router::new().route("/bar", get(|| async {})))
383 .oneshot(req)
384 }),
385 );
386
387 let client = TestClient::new(app);
388
389 let res = client.get("/foo/bar").await;
390 assert_eq!(res.status(), StatusCode::OK);
391 }
392
393 #[crate::test]
394 async fn cant_extract_in_fallback() {
395 async fn handler(path: Option<MatchedPath>, req: Request) {
396 assert!(path.is_none());
397 assert!(req.extensions().get::<MatchedPath>().is_none());
398 }
399
400 let app = Router::new().fallback(handler);
401
402 let client = TestClient::new(app);
403
404 let res = client.get("/foo/bar").await;
405 assert_eq!(res.status(), StatusCode::OK);
406 }
407
408 #[crate::test]
409 async fn matching_colon() {
410 let app = Router::new().route(
411 "/:foo",
412 get(|path: MatchedPath| async move { path.as_str().to_owned() }),
413 );
414
415 let client = TestClient::new(app);
416
417 let res = client.get("/:foo").await;
418 assert_eq!(res.status(), StatusCode::OK);
419 assert_eq!(res.text().await, "/:foo");
420
421 let res = client.get("/:bar").await;
422 assert_eq!(res.status(), StatusCode::NOT_FOUND);
423
424 let res = client.get("/foo").await;
425 assert_eq!(res.status(), StatusCode::NOT_FOUND);
426 }
427
428 #[crate::test]
429 async fn matching_asterisk() {
430 let app = Router::new().route(
431 "/*foo",
432 get(|path: MatchedPath| async move { path.as_str().to_owned() }),
433 );
434
435 let client = TestClient::new(app);
436
437 let res = client.get("/*foo").await;
438 assert_eq!(res.status(), StatusCode::OK);
439 assert_eq!(res.text().await, "/*foo");
440
441 let res = client.get("/*bar").await;
442 assert_eq!(res.status(), StatusCode::NOT_FOUND);
443
444 let res = client.get("/foo").await;
445 assert_eq!(res.status(), StatusCode::NOT_FOUND);
446 }
447}