如何在actix-web 1.0中间件中修改响应主体?

时间:2019-06-04 18:34:18

标签: rust actix-web

我想在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”。如果可以做到这一点,我可以完成我想做的其余工作。

Complete code

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

1 个答案:

答案 0 :(得分:1)

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

  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);

希望有帮助!