Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Implement OptionalFromRequest for the Json extractor #3142

Merged
merged 6 commits into from
Jan 3, 2025
Merged
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
4 changes: 4 additions & 0 deletions axum/CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
23 changes: 23 additions & 0 deletions axum/src/json.rs
Original file line number Diff line number Diff line change
@@ -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::{
Expand Down Expand Up @@ -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)?))
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

this causes a mismatching JSON body to return an error instead of None, is that intentional?

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

is this in reference to the previous CR comment? by mismatch do you mean an empty body here?

} 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
Expand Down