actix / actix-web

Actix Web is a powerful, pragmatic, and extremely fast web framework for Rust.

Home Page:https://actix.rs

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

[How to] Middleware `Response body` manipulation.

0rangeFox opened this issue · comments

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()
}