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

Add a JSON extractor #15

Closed
dzamlo opened this issue Dec 28, 2023 · 2 comments
Closed

Add a JSON extractor #15

dzamlo opened this issue Dec 28, 2023 · 2 comments

Comments

@dzamlo
Copy link
Contributor

dzamlo commented Dec 28, 2023

It can be useful to accept JSON in request.

Here is a minimal implementation using serde_json_core

use serde_json_core::de::Error as JsonError;

pub struct JsonRejection(JsonError);

impl IntoResponse for JsonRejection {
    async fn write_to<W: picoserve::response::ResponseWriter>(
        self,
        response_writer: W,
    ) -> Result<picoserve::ResponseSent, W::Error> {
        (
            picoserve::response::status::BAD_REQUEST,
            format_args!("Request Body is not valid JSON: {}", self.0),
        )
            .write_to(response_writer)
            .await
    }
}

pub struct Json<T: serde::de::DeserializeOwned>(pub T);

impl<State, T: serde::de::DeserializeOwned> FromRequest<State> for Json<T> {
    type Rejection = JsonRejection;

    async fn from_request(
        _state: &State,
        request: &Request<'_>,
    ) -> Result<Json<T>, JsonRejection> {
        serde_json_core::from_slice(request.body)
            .map(|(v, _)| Self(v))
            .map_err(JsonRejection)
    }
}
@sammhicks
Copy link
Owner

Looks good! I'm waiting on rust-embedded-community/serde-json-core#79 at the moment, but once it's merged, I'm planning on supporting parsing JSON bodies

@vpikulik
Copy link

please have a look: https://github.com/sammhicks/picoserve/pull/33/files

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

3 participants