Add NestedUri (#161)

Fixes https://github.com/tokio-rs/axum/issues/159
This commit is contained in:
David Pedersen
2021-08-08 14:45:31 +02:00
committed by GitHub
parent 8013165908
commit b4bdddf9d2
6 changed files with 86 additions and 2 deletions
+1
View File
@@ -278,6 +278,7 @@ pub use self::{
path::Path,
query::Query,
raw_query::RawQuery,
request_parts::NestedUri,
request_parts::{Body, BodyStream},
};
#[doc(no_inline)]
+10
View File
@@ -108,6 +108,16 @@ 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)]
+43 -1
View File
@@ -1,4 +1,4 @@
use super::{rejection::*, take_body, FromRequest, RequestParts};
use super::{rejection::*, take_body, Extension, FromRequest, RequestParts};
use async_trait::async_trait;
use bytes::Bytes;
use futures_util::stream::Stream;
@@ -74,6 +74,48 @@ where
}
}
/// Extractor that gets the request URI for a nested service.
///
/// This is necessary since [`Uri`](http::Uri), when used as an extractor, will
/// always be the full URI.
///
/// # Example
///
/// ```
/// use axum::{prelude::*, extract::NestedUri, http::Uri};
///
/// let api_routes = route(
/// "/users",
/// get(|uri: Uri, NestedUri(nested_uri): NestedUri| async {
/// // `uri` is `/api/users`
/// // `nested_uri` is `/users`
/// }),
/// );
///
/// let app = nest("/api", api_routes);
/// # async {
/// # axum::Server::bind(&"".parse().unwrap()).serve(app.into_make_service()).await.unwrap();
/// # };
/// ```
#[derive(Debug, Clone)]
pub struct NestedUri(pub Uri);
#[async_trait]
impl<B> FromRequest<B> for NestedUri
where
B: Send,
{
type Rejection = NotNested;
async fn from_request(req: &mut RequestParts<B>) -> Result<Self, Self::Rejection> {
let uri = Extension::<Self>::from_request(req)
.await
.map_err(|_| NotNested)?
.0;
Ok(uri)
}
}
#[async_trait]
impl<B> FromRequest<B> for Version
where