Accessing a form in middleware #1475
-
Hi - in my handlers I accept a Is this possible? I know I can get extensions in the middleware via Thanks! |
Beta Was this translation helpful? Give feedback.
Replies: 2 comments 2 replies
-
Its possible but hard since the middleware would have to consume the request body and insert it back before calling the handler. Instead I'd recommend writing your own extractor that internally calls |
Beta Was this translation helpful? Give feedback.
-
thanks @jplatte. I ended up hooking up cobbling together something that worked:
#[async_trait]
impl<B> FromRequest<B> for ActionFormExtractor
where
B: HttpBody + Send,
B::Data: Send,
B::Error: Into<BoxError>,
{
type Rejection = (StatusCode, &'static str);
async fn from_request(req: &mut RequestParts<B>) -> Result<Self, Self::Rejection> {
let Form(mut raw_form): Form<RawActionForm> =
Form::from_request(req).await.map_err(|e| {
error!("failed to create raw action form: {}", &e);
(StatusCode::BAD_REQUEST, "unknown error")
})?;
raw_form.prune();
let action = serde_json::from_str(&raw_form.action).map_err(|e| {
error!("error {} parsing JSON: {}", e, &raw_form.action);
(StatusCode::BAD_REQUEST, "JSON error")
})?;
let form = ActionForm {
action,
note: raw_form.note.clone(),
unacceptable_reason_id: raw_form.unacceptable_reason_id,
};
Ok(ActionFormExtractor(form))
}
} so the handlers now accept |
Beta Was this translation helpful? Give feedback.
Its possible but hard since the middleware would have to consume the request body and insert it back before calling the handler.
Instead I'd recommend writing your own extractor that internally calls
Form
and does whatever processing needed there. Then you can use that extractor in your handlers instead.