Change nested routes to see the URI with prefix stripped (#197)

This commit is contained in:
David Pedersen
2021-08-18 09:48:36 +02:00
committed by GitHub
parent cb637f1124
commit e22045d42f
10 changed files with 255 additions and 55 deletions
+1 -1
View File
@@ -316,7 +316,7 @@ pub use self::{
path::Path,
query::Query,
raw_query::RawQuery,
request_parts::NestedUri,
request_parts::OriginalUri,
request_parts::{Body, BodyStream},
};
#[doc(no_inline)]
-10
View File
@@ -102,16 +102,6 @@ define_rejection! {
pub struct InvalidFormContentType;
}
define_rejection! {
#[status = INTERNAL_SERVER_ERROR]
#[body = "`NestedUri` extractor used for route that isn't nested"]
/// Rejection type used if you try and extract [`NestedUri`] from a route that
/// isn't nested.
///
/// [`NestedUri`]: crate::extract::NestedUri
pub struct NotNested;
}
/// Rejection type for [`Path`](super::Path) if the capture route
/// param didn't have the expected type.
#[derive(Debug)]
+10 -10
View File
@@ -82,10 +82,10 @@ where
}
}
/// Extractor that gets the request URI for a nested service.
/// Extractor that gets the original request URI regardless of nesting.
///
/// This is necessary since [`Uri`](http::Uri), when used as an extractor, will
/// always be the full URI.
/// have the prefix stripped if used in a nested service.
///
/// # Example
///
@@ -94,15 +94,15 @@ where
/// handler::get,
/// route,
/// routing::{nest, RoutingDsl},
/// extract::NestedUri,
/// extract::OriginalUri,
/// http::Uri
/// };
///
/// let api_routes = route(
/// "/users",
/// get(|uri: Uri, NestedUri(nested_uri): NestedUri| async {
/// // `uri` is `/api/users`
/// // `nested_uri` is `/users`
/// get(|uri: Uri, OriginalUri(original_uri): OriginalUri| async {
/// // `uri` is `/users`
/// // `original_uri` is `/api/users`
/// }),
/// );
///
@@ -112,19 +112,19 @@ where
/// # };
/// ```
#[derive(Debug, Clone)]
pub struct NestedUri(pub Uri);
pub struct OriginalUri(pub Uri);
#[async_trait]
impl<B> FromRequest<B> for NestedUri
impl<B> FromRequest<B> for OriginalUri
where
B: Send,
{
type Rejection = NotNested;
type Rejection = Infallible;
async fn from_request(req: &mut RequestParts<B>) -> Result<Self, Self::Rejection> {
let uri = Extension::<Self>::from_request(req)
.await
.map_err(|_| NotNested)?
.unwrap_or_else(|_| Extension(OriginalUri(req.uri().clone())))
.0;
Ok(uri)
}