3

我想修改 Actix-Web 中的响应正文。我已经实现了 v1.0.0 中间件,但到目前为止我还没有成功更改响应正文。

我尝试了两种基本方法:返回一个新的ServiceResponse并使用方法链ServiceResponse尝试设置一个新的主体。这两种方法都导致了我无法解决的各种编译器错误和移动违规。虽然我是 Rust 新手,但我团队的其他成员更有经验,也无法应对这些挑战。我找不到任何正确的例子。

这是我的call().

fn call(&mut self, req: ServiceRequest) -> Self::Future {
    let content_type = req.get_header_value("content-type");

    println!(
        "Request Started: {}; content type: {};",
        req.path(),
        content_type
    );

    Box::new(self.service.call(req).and_then(move |mut res| {
        match res.response().error() {
            Some(e) => {
                println!(
                    "Response: Error Code: {}; content type: {};",
                    res.status(),
                    content_type
                );

                dbg!(e);

                // I'd really like to modify the response body here.

                return Ok(res);
            }
            None => {
                println!("Middleware detected the response is not an error. ");
                return Ok(res);
            }
        }
    }))
}

我想将响应正文修改为文本“fredbob”。如果我能做到这一点,我就可以完成我想做的其余事情。

完整代码

use actix_service::{Service, Transform};
use actix_web::http::StatusCode;
use actix_web::{dev::ServiceRequest, dev::ServiceResponse, Error, HttpResponse};
use futures::future::{ok, FutureResult};
use futures::{Future, Poll};

use serde::Serialize;
use serde_json;

pub trait Headers {
    fn get_header_value(&self, name: &str) -> String;
}

impl Headers for ServiceRequest {
    fn get_header_value(&self, name: &str) -> String {
        self.headers()
            .get(name)
            .unwrap()
            .to_str()
            .unwrap()
            .to_string()
    }
}

// There are two step in middleware processing.
// 1. Middleware initialization, middleware factory get called with
//    next service in chain as parameter.
// 2. Middleware's call method get called with normal request.
pub struct SayHi;

// Middleware factory is `Transform` trait from actix-service crate
// `S` - type of the next service
// `B` - type of response's body
impl<S, B> Transform<S> for SayHi
where
    S: Service<Request = ServiceRequest, Response = ServiceResponse<B>, Error = Error>,
    S::Future: 'static,
    B: 'static,
{
    type Request = ServiceRequest;
    type Response = ServiceResponse<B>;
    type Error = Error;
    type InitError = ();
    type Transform = SayHiMiddleware<S>;
    type Future = FutureResult<Self::Transform, Self::InitError>;

    fn new_transform(&self, service: S) -> Self::Future {
        ok(SayHiMiddleware { service })
    }
}

pub struct SayHiMiddleware<S> {
    service: S,
}

fn is_error(status: StatusCode) -> bool {
    status.as_u16() >= 400
}

impl<S, B> Service for SayHiMiddleware<S>
where
    S: Service<Request = ServiceRequest, Response = ServiceResponse<B>, Error = Error>,
    S::Future: 'static,
    B: 'static,
{
    type Request = ServiceRequest;
    type Response = ServiceResponse<B>;
    type Error = Error;
    type Future = Box<Future<Item = Self::Response, Error = Self::Error>>;

    fn poll_ready(&mut self) -> Poll<(), Self::Error> {
        self.service.poll_ready()
    }

    fn call(&mut self, req: ServiceRequest) -> Self::Future {
        let content_type = req.get_header_value("content-type");

        println!(
            "Request Started: {}; content type: {};",
            req.path(),
            content_type
        );

        Box::new(self.service.call(req).and_then(move |mut res| {
            match res.response().error() {
                Some(e) => {
                    println!(
                        "Response: Error Code: {}; content type: {};",
                        res.status(),
                        content_type
                    );

                    dbg!(e);

                    // I'd really like to modify the response body here.

                    return Ok(res);
                }
                None => {
                    println!("Middleware detected the response is not an error. ");
                    return Ok(res);
                }
            }
        }))
    }
}
4

2 回答 2

3

上面发布的解决方案不再适用于更高版本的Actix。在4.0.0-beta.14中,在您的中间件中,您可以通过以下方式捕获请求:

let mut request_body = BytesMut::new();
while let Some(chunk) = req.take_payload().next().await {
    request_body.extend_from_slice(&chunk?);
}

let mut orig_payload = Payload::empty();
orig_payload.unread_data(request_body.freeze());
req.set_payload(actix_http::Payload::from(orig_payload));

您可以通过以下方式捕获响应:

let _body_data =
    match str::from_utf8(&body::to_bytes(res.into_body()).await?){
    Ok(str) => {
        str
    }
    Err(_) => {
        "Unknown"
    }
};

注意:拉取请求/响应将意味着您使用请求/响应,因此您需要更改它并创建一个新的请求/响应。

然后您可以返回一个新的响应:

let new_request = res.request().clone();

let new_response = HttpResponseBuilder::new(StatusCode::BAD_REQUEST)
          .insert_header((header::CONTENT_TYPE, "application/json"))
          .body("New body data");

Ok(ServiceResponse::new(
    new_request,
    new_response
))

我在这里发布了一个完整的例子:

如何在 actix_web 中间件中打印响应正文?

于 2021-12-13T20:13:33.203 回答
2

您可以尝试这两种方法之一。他们都为我工作:

  1. 使用map_body方法来自ServiceResponse
let new_res = res.map_body(|_head, _body| {
    ResponseBody::Other(Body::Message(Box::new("fredbob")))
});

return Ok(new_res);
  1. 访问HttpRequest,克隆它,并构建一个新的ServiceResponse
let new_res = ServiceResponse::new(
    res.request().clone(),
    HttpResponse::Ok().body("fredbob").into_body(),
);

return Ok(new_res);

希望能帮助到你!

于 2019-08-16T17:46:05.163 回答