-
Notifications
You must be signed in to change notification settings - Fork 36
Closed
Description
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)
}
}
Metadata
Metadata
Assignees
Labels
No labels