mirror of
https://github.com/tokio-rs/axum.git
synced 2026-09-07 00:00:12 +02:00
Implement OptionalFromRequest for the Json extractor (#3142)
This commit is contained in:
@@ -7,6 +7,10 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
|
|||||||
|
|
||||||
# Unreleased
|
# Unreleased
|
||||||
|
|
||||||
|
- **added:** Implement `OptionalFromRequest` for `Json` ([#3142])
|
||||||
|
|
||||||
|
[#3142]: https://github.com/tokio-rs/axum/pull/3142
|
||||||
|
|
||||||
# 0.8.0
|
# 0.8.0
|
||||||
|
|
||||||
## since rc.1
|
## since rc.1
|
||||||
|
|||||||
@@ -1,5 +1,6 @@
|
|||||||
use crate::extract::Request;
|
use crate::extract::Request;
|
||||||
use crate::extract::{rejection::*, FromRequest};
|
use crate::extract::{rejection::*, FromRequest};
|
||||||
|
use axum_core::extract::OptionalFromRequest;
|
||||||
use axum_core::response::{IntoResponse, Response};
|
use axum_core::response::{IntoResponse, Response};
|
||||||
use bytes::{BufMut, Bytes, BytesMut};
|
use bytes::{BufMut, Bytes, BytesMut};
|
||||||
use http::{
|
use http::{
|
||||||
@@ -112,6 +113,28 @@ where
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
impl<T, S> OptionalFromRequest<S> for Json<T>
|
||||||
|
where
|
||||||
|
T: DeserializeOwned,
|
||||||
|
S: Send + Sync,
|
||||||
|
{
|
||||||
|
type Rejection = JsonRejection;
|
||||||
|
|
||||||
|
async fn from_request(req: Request, state: &S) -> Result<Option<Self>, Self::Rejection> {
|
||||||
|
let headers = req.headers();
|
||||||
|
if headers.get(header::CONTENT_TYPE).is_some() {
|
||||||
|
if json_content_type(headers) {
|
||||||
|
let bytes = Bytes::from_request(req, state).await?;
|
||||||
|
Ok(Some(Self::from_bytes(&bytes)?))
|
||||||
|
} else {
|
||||||
|
Err(MissingJsonContentType.into())
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
Ok(None)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
fn json_content_type(headers: &HeaderMap) -> bool {
|
fn json_content_type(headers: &HeaderMap) -> bool {
|
||||||
let content_type = if let Some(content_type) = headers.get(header::CONTENT_TYPE) {
|
let content_type = if let Some(content_type) = headers.get(header::CONTENT_TYPE) {
|
||||||
content_type
|
content_type
|
||||||
|
|||||||
Reference in New Issue
Block a user