我一直在尝试根据Actix-web文档中列出的示例编译SayHi
中间件:https://actix.rs/docs/middleware/。问题是在最新版本的Actix-web(3.3.2)和Rust(1.55)中,这段代码无法编译,模板缺少参数(大概是因为请求类型已经移动到它们?),即使我将请求类型移动到正确的位置,其他内容也会中断。
如何在最新版本的actix-web中实现像SayHi
这样的简单中间件?
我是Rust的新手,所以如果我遗漏了一些明显的东西,请告诉我,但我已经在这两天了,我似乎无法找到或制作任何代码,成功地在最新版本中创建一个简单的actix-web中间件。
这是截至2021年10月16日的actix文档中的示例代码:
use std::pin::Pin;
use std::task::{Context, Poll};
use actix_service::{Service, Transform};
use actix_web::{dev::ServiceRequest, dev::ServiceResponse, Error};
use futures::future::{ok, Ready};
use futures::Future;
pub struct SayHi;
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 = Ready<Result<Self::Transform, Self::InitError>>;
fn new_transform(&self, service: S) -> Self::Future {
ok(SayHiMiddleware { service })
}
}
pub struct SayHiMiddleware<S> {
service: S,
}
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 = Pin<Box<dyn Future<Output = Result<Self::Response, Self::Error>>>>;
fn poll_ready(&mut self, cx: &mut Context<'_>) -> Poll<Result<(), Self::Error>> {
self.service.poll_ready(cx)
}
fn call(&mut self, req: ServiceRequest) -> Self::Future {
println!("Hi from start. You requested: {}", req.path());
let fut = self.service.call(req);
Box::pin(async move {
let res = fut.await?;
println!("Hi from response");
Ok(res)
})
}
}
1条答案
按热度按时间gwbalxhn1#
事实证明,这个解决方案确实是微不足道的。
而不是从
actix-service
导入Service
和Transform
的定义,后者已经过时(或更新?)定义,它们应该直接从actix_web
子模块dev
导入,如下所示: