rust 如何在最新版本(3.3.2)中实现Actix-web中间件?

3df52oht  于 2023-10-20  发布在  其他
关注(0)|答案(1)|浏览(114)

我一直在尝试根据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)
        })
    }
}
gwbalxhn

gwbalxhn1#

事实证明,这个解决方案确实是微不足道的。
而不是从actix-service导入ServiceTransform的定义,后者已经过时(或更新?)定义,它们应该直接从actix_web子模块dev导入,如下所示:

use std::pin::Pin;
use std::task::{Context, Poll};

// use actix_service::{Service, Transform};
use actix_web::dev::{ServiceRequest, ServiceResponse, Service, Transform};
use actix_web::Error;
use futures::future::{ok, Ready};
use futures::Future;

相关问题