我想修改 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);
}
}
}))
}
}