[How to] Middleware `Response body` manipulation.
0rangeFox opened this issue · comments
João Fernandes commented
Hey folks 👋! The title already tells what I am looking for, basically I have this bit of code, but I would say that only the manipulate_body
function is what will be used to be analyzed. I've already seen a lot of issues (#2856, #3166, #3227) and examples, but none of them achieve what I want to do. Can anyone help me with this part? Thanks for any suggestions and opinions.
// ...
forward_ready!(service);
fn call(&self, mut req: ServiceRequest) -> Self::Future {
let service = Rc::clone(&self.service);
Box::pin(async move {
let mut res: ServiceResponse<B> = service.call(req).await?;
res = manipulate_body(&res);
Ok(res)
})
}
// ...
fn manipulate_body<B: MessageBody>(res: &ServiceResponse<B>) -> ServiceResponse<B> {
// Read body bytes
let body_bytes = res.response().body();
let mut new_body: Value = serde_json::from_slice(&body_bytes).unwrap();
new_body["test"] = Value::String("anything".to_owned());
// Destructures ServiceResponse into request and response components
let (req, res) = res.into_parts();
// Create a new response with the modified body
let res: HttpResponse<B> = res.set_body(&new_body.to_string()).map_into_boxed_body();
// Create a new ServiceResponse with the modified response
ServiceResponse::new(req, res).map_into_right_body()
}