Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 0 additions & 1 deletion axum/src/docs/extract.md
Original file line number Diff line number Diff line change
Expand Up @@ -686,5 +686,4 @@ logs, enable the `tracing` feature for axum (enabled by default) and the
[customize-extractor-error]: https://github.com/tokio-rs/axum/blob/main/examples/customize-extractor-error/src/main.rs
[`HeaderMap`]: https://docs.rs/http/latest/http/header/struct.HeaderMap.html
[`Request`]: https://docs.rs/http/latest/http/struct.Request.html
[`RequestParts::body_mut`]: crate::extract::RequestParts::body_mut
[`JsonRejection::JsonDataError`]: rejection::JsonRejection::JsonDataError
34 changes: 31 additions & 3 deletions axum/src/extract/raw_form.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
use axum_core::extract::{FromRequest, Request};
use axum_core::extract::{FromRequest, OptionalFromRequest, Request};
use bytes::Bytes;
use http::Method;
use http::{header, Method};

use super::{
has_content_type,
Expand Down Expand Up @@ -36,7 +36,7 @@ where
type Rejection = RawFormRejection;

async fn from_request(req: Request, state: &S) -> Result<Self, Self::Rejection> {
if req.method() == Method::GET {
if req.method() == Method::GET || req.method() == Method::HEAD {
if let Some(query) = req.uri().query() {
return Ok(Self(Bytes::copy_from_slice(query.as_bytes())));
}
Expand All @@ -52,6 +52,34 @@ where
}
}

impl<S> OptionalFromRequest<S> for RawForm
where
S: Send + Sync,
{
type Rejection = RawFormRejection;

async fn from_request(req: Request, state: &S) -> Result<Option<Self>, Self::Rejection> {
if req.method() == Method::GET || req.method() == Method::HEAD {
if let Some(query) = req.uri().query() {
return Ok(Some(Self(Bytes::copy_from_slice(query.as_bytes()))));
}

Ok(None)
} else {
let headers = req.headers();
if headers.get(header::CONTENT_TYPE).is_some() {
if !has_content_type(headers, &mime::APPLICATION_WWW_FORM_URLENCODED) {
return Err(InvalidFormContentType.into());
}

Ok(Some(Self(Bytes::from_request(req, state).await?)))
} else {
Ok(None)
}
}
}
}

#[cfg(test)]
mod tests {
use axum_core::body::Body;
Expand Down
55 changes: 52 additions & 3 deletions axum/src/form.rs
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
use crate::extract::Request;
use crate::extract::{rejection::*, FromRequest, RawForm};
use axum_core::extract::OptionalFromRequest;
use axum_core::response::{IntoResponse, Response};
use axum_core::RequestExt;
use http::header::CONTENT_TYPE;
Expand Down Expand Up @@ -105,6 +106,42 @@ where
}
}

impl<T, S> OptionalFromRequest<S> for Form<T>
where
T: DeserializeOwned,
S: Send + Sync,
{
type Rejection = FormRejection;

async fn from_request(req: Request, _state: &S) -> Result<Option<Self>, Self::Rejection> {
let is_get_or_head =
req.method() == http::Method::GET || req.method() == http::Method::HEAD;

match req.extract().await {
Ok(Some(RawForm(bytes))) => {
let deserializer =
serde_urlencoded::Deserializer::new(form_urlencoded::parse(&bytes));
let value = serde_path_to_error::deserialize(deserializer).map_err(
|err| -> FormRejection {
if is_get_or_head {
FailedToDeserializeForm::from_err(err).into()
} else {
FailedToDeserializeFormBody::from_err(err).into()
}
},
)?;

Ok(Some(Form(value)))
}
Ok(None) => Ok(None),
Err(RawFormRejection::BytesRejection(r)) => Err(FormRejection::BytesRejection(r)),
Err(RawFormRejection::InvalidFormContentType(r)) => {
Err(FormRejection::InvalidFormContentType(r))
}
}
}
}

impl<T> IntoResponse for Form<T>
where
T: Serialize,
Expand Down Expand Up @@ -153,7 +190,13 @@ mod tests {
.uri(uri.as_ref())
.body(Body::empty())
.unwrap();
assert_eq!(Form::<T>::from_request(req, &()).await.unwrap().0, value);
assert_eq!(
<Form::<T> as FromRequest<_>>::from_request(req, &())
.await
.unwrap()
.0,
value
);
}

async fn check_body<T: Serialize + DeserializeOwned + PartialEq + Debug>(value: T) {
Expand All @@ -163,7 +206,13 @@ mod tests {
.header(CONTENT_TYPE, APPLICATION_WWW_FORM_URLENCODED.as_ref())
.body(Body::from(serde_urlencoded::to_string(&value).unwrap()))
.unwrap();
assert_eq!(Form::<T>::from_request(req, &()).await.unwrap().0, value);
assert_eq!(
<Form::<T> as FromRequest<_>>::from_request(req, &())
.await
.unwrap()
.0,
value
);
}

#[crate::test]
Expand Down Expand Up @@ -232,7 +281,7 @@ mod tests {
))
.unwrap();
assert!(matches!(
Form::<Pagination>::from_request(req, &())
<Form::<Pagination> as FromRequest<_>>::from_request(req, &())
.await
.unwrap_err(),
FormRejection::InvalidFormContentType(InvalidFormContentType)
Expand Down
Loading