Skip to content
Myr

Add method filtering to route_with_tsr (#3586)

Before adoption: this commit came in with the history the project adopted, so no landing records it.

authored by Jonas Platte · committed by GitHub · parent 051628c · Browse files · 5 files+120 added−10 removed
This commit

State

Before adoption: this commit came in with the history the project adopted, so no landing records it.

Diff stats

5 files+120 added−10 removed

  • other:+120 added−10 removed

5 files+120 added−10 removed

modified:axum/src/routing/method_routing.rs+68 added-1 removed
658 unmodified lines
659 self.fallback = Fallback::BoxedHandler(BoxedIntoRoute::from_handler(handler));660 self661 }662663 /// Get a [`MethodFilter`] for the methods that this `MethodRouter` has664 /// custom code for.665 ///666 /// Note that `MethodRouter`'s [`Service`] implementation never fails (it667 /// always creates an HTTP response) based on which HTTP method was used.668 /// However, the information which methods have the default behavior of669 /// returning HTTP 405 is stored, and can be queried with this method.670 ///671 /// Returns `None` if the `MethodRouter` was constructed with [`any`] or672 /// has had a [`fallback`][Self::fallback] set.673 pub fn method_filter(&self) -> Option<MethodFilter> {674 let Self {675 get,676 head,677 delete,678 options,679 patch,680 post,681 put,682 trace,683 connect,684 fallback,685 allow_header: _,686 } = self;687688 if !fallback.is_default() {689 return None;690 }691692 let filter = [693 (get, MethodFilter::GET),694 (head, MethodFilter::HEAD),695 (delete, MethodFilter::DELETE),696 (options, MethodFilter::OPTIONS),697 (patch, MethodFilter::PATCH),698 (post, MethodFilter::POST),699 (put, MethodFilter::PUT),700 (trace, MethodFilter::TRACE),701 (connect, MethodFilter::CONNECT),702 ]703 .into_iter()704 .filter_map(|(ep, f)| ep.is_some().then_some(f))705 .reduce(MethodFilter::or)706 .expect("can't create a MethodRouter with all-default handlers");707708 Some(filter)709 }710711 /// Add a fallback [`Handler`] if no custom one has been provided.712 pub(crate) fn default_fallback<H, T>(self, handler: H) -> Self713 where714 H: Handler<T, S>,
171 unmodified lines
886 if out.is_some() {887 panic!(888 "Overlapping method route. Cannot add two method routes that both handle \889 `{method_name}`",842 )890 );891 }892 *out = endpoint.clone();893 for method in methods {894 append_allow_header(allow_header, method);
766 unmodified lines
1661 assert_eq!(status, StatusCode::OK);1662 assert_eq!(text, "state");1663 }16641665 #[test]1666 fn method_filter() {1667 let router: MethodRouter = get(|| async {});1668 assert_eq!(router.method_filter(), Some(MethodFilter::GET));16691670 let router: MethodRouter = get(|| async {}).head(|| async {}).post(|| async {});1671 assert_eq!(1672 router.method_filter(),1673 Some(1674 MethodFilter::GET1675 .or(MethodFilter::HEAD)1676 .or(MethodFilter::POST)1677 )1678 );16791680 let router: MethodRouter = any(|| async {});1681 assert_eq!(router.method_filter(), None);1682 }16831684 async fn call<S>(method: Method, svc: &mut S) -> (StatusCode, HeaderMap, String)1685 where1686 S: Service<Request, Error = Infallible>,1687 S::Response: IntoResponse,
28 unmodified lines
modified:axum/src/routing/mod.rs+4 added
738 unmodified lines
739 route.oneshot_inner_owned(req)740 }741 }742 }743744 fn is_default(&self) -> bool {745 matches!(self, Self::Default(..))746 }747}748749impl<S, E> Clone for Fallback<S, E> {750 fn clone(&self) -> Self {
73 unmodified lines
modified:axum/CHANGELOG.md+2 added
13 unmodified lines
14- **breaking:** `axum::serve` future output type has been adjusted to remove `io::Result`15 (never returned `Err`) and be an uninhabited type if `with_graceful_shutdown` is not used16 (because it was already never terminating if that method wasn't used) ([#3601])17- **added:** New `ListenerExt::limit_connections` allows limiting concurrent `axum::serve` connections ([#3489])18- **added:** `MethodRouter::method_filter` ([#3586])19- **changed:** `serve` has an additional generic argument and can now work with any response body20 type, not just `axum::body::Body` ([#3205])2122[#3158]: https://github.com/tokio-rs/axum/pull/3158
1 unmodified line
24[#3205]: https://github.com/tokio-rs/axum/pull/320525[#3478]: https://github.com/tokio-rs/axum/pull/347826[#3601]: https://github.com/tokio-rs/axum/pull/360127[#3489]: https://github.com/tokio-rs/axum/pull/348928[#3586]: https://github.com/tokio-rs/axum/pull/35862930# 0.8.83132- Clarify documentation for `Router::route_layer` ([#3567])
2395 unmodified lines
modified:axum-extra/src/routing/mod.rs+34 added-9 removed
1 unmodified line
23use axum::{4 extract::{OriginalUri, Request},5 response::{IntoResponse, Redirect, Response},6 routing::{any, MethodRouter},6 routing::{any, on, MethodFilter, MethodRouter},7 Router,8};9use http::{uri::PathAndQuery, StatusCode, Uri};10use std::{borrow::Cow, convert::Infallible};
324 unmodified lines
335 where336 Self: Sized,337 {338 validate_tsr_path(path);339 let method_filter = method_router.method_filter();340 self = self.route(path, method_router);340 add_tsr_redirect_route(self, path)341 add_tsr_redirect_route(self, path, method_filter)342 }343344 #[track_caller]345 fn route_service_with_tsr<T>(mut self, path: &str, service: T) -> Self
4 unmodified lines
350 Self: Sized,351 {352 validate_tsr_path(path);353 self = self.route_service(path, service);353 add_tsr_redirect_route(self, path)354 add_tsr_redirect_route(self, path, None)355 }356}357358#[track_caller]
2 unmodified lines
361 panic!("Cannot add a trailing slash redirect route for `/`")362 }363}364364fn add_tsr_redirect_route<S>(router: Router<S>, path: &str) -> Router<S>365fn add_tsr_redirect_route<S>(366 router: Router<S>,367 path: &str,368 method_filter: Option<MethodFilter>,369) -> Router<S>370where371 S: Clone + Send + Sync + 'static,372{373 async fn redirect_handler(OriginalUri(uri): OriginalUri) -> Response {
9 unmodified lines
383 StatusCode::BAD_REQUEST.into_response()384 }385 }386382 if let Some(path_without_trailing_slash) = path.strip_suffix('/') {383 router.route(path_without_trailing_slash, any(redirect_handler))387 let _slot;388 let redirect_path = if let Some(without_slash) = path.strip_suffix('/') {389 without_slash390 } else {385 router.route(&format!("{path}/"), any(redirect_handler))386 }391 // FIXME: Can return `&format!(...)` directly when MSRV is updated392 _slot = format!("{path}/");393 &_slot394 };395396 let method_router = match method_filter {397 Some(f) => on(f, redirect_handler),398 None => any(redirect_handler),399 };400401 router.route(redirect_path, method_router)402}403404/// Map the path of a `Uri`.405///
25 unmodified lines
431#[cfg(test)]432mod tests {433 use super::*;434 use crate::test_helpers::*;420 use axum::{extract::Path, routing::get};435 use axum::{436 extract::Path,437 routing::{get, post},438 };439440 #[tokio::test]441 async fn test_tsr() {442 let app = Router::new()
75 unmodified lines
518 assert_eq!(res.headers()["location"], "/neko/nyan/");519 }520521 #[test]522 fn tsr_independent_route_registration() {523 let _: Router = Router::new()524 .route_with_tsr("/x", get(|| async {}))525 .route_with_tsr("/x", post(|| async {}));526 }527528 #[test]529 #[should_panic = "Cannot add a trailing slash redirect route for `/`"]530 fn tsr_at_root() {531 let _: Router = Router::new().route_with_tsr("/", get(|| async move {}));532 }
1 unmodified line
modified:axum-extra/CHANGELOG.md+12 added
7 unmodified lines
8# Unreleased910- **breaking:** Remove the deprecated `Host`, `Scheme` and `OptionalPath`11 extractors ([#3599])12- **breaking:** Change `routing::RouterExt::route_with_tsr` to only redirect13 the HTTP methods that the supplied `MethodRouter` handles. This allows the14 following pattern which lead to a panic before because the two15 `route_with_tsr` calls would both attempt to register a method-independent16 redirect ([#3586]):1718 ```rust19 Router::new()20 .route_with_tsr("/path", get(/* handler */))21 .route_with_tsr("/path", post(/* handler */))22 ```2324[#3599]: https://github.com/tokio-rs/axum/pull/359925[#3586]: https://github.com/tokio-rs/axum/pull/35862627# 0.12.52829- **fixed:** `JsonLines` now correctly respects the default body limit ([#3591])
536 unmodified lines