mirror of
https://github.com/tokio-rs/axum.git
synced 2025-04-26 13:56:22 +02:00
Implement OptionalFromRequest
for the Json extractor (#3142)
This commit is contained in:
parent
e0b55d7503
commit
ef0b99b6a0
2 changed files with 27 additions and 0 deletions
axum
|
@ -7,6 +7,10 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
|
|||
|
||||
# Unreleased
|
||||
|
||||
- **added:** Implement `OptionalFromRequest` for `Json` ([#3142])
|
||||
|
||||
[#3142]: https://github.com/tokio-rs/axum/pull/3142
|
||||
|
||||
# 0.8.0
|
||||
|
||||
## since rc.1
|
||||
|
|
|
@ -1,5 +1,6 @@
|
|||
use crate::extract::Request;
|
||||
use crate::extract::{rejection::*, FromRequest};
|
||||
use axum_core::extract::OptionalFromRequest;
|
||||
use axum_core::response::{IntoResponse, Response};
|
||||
use bytes::{BufMut, Bytes, BytesMut};
|
||||
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 {
|
||||
let content_type = if let Some(content_type) = headers.get(header::CONTENT_TYPE) {
|
||||
content_type
|
||||
|
|
Loading…
Add table
Reference in a new issue