从 Actix Web 应用程序中间件访问应用程序状态

Application state access from an Actix web application middleware

我有一个简单的中间件,用于访问应用程序的全局状态以执行身份验证令牌的验证:

use actix_web;
use actix_web::HttpMessage;

pub struct Authenticator;

impl<S> actix_web::middleware::Middleware<S> for Authenticator {
    fn start(
        &self,
        request: &mut actix_web::HttpRequest<S>,
    ) -> actix_web::Result<actix_web::middleware::Started> {
        //let _state = request.state() as &::application::State;
        match request.headers().get("Authentication") {
            Some(_) => Ok(actix_web::middleware::Started::Done),
            None => Err(::view::error(
                "No authentication header provided",
                actix_web::http::StatusCode::FORBIDDEN,
            )),
        }
    }
}

注释的字符串显示了我是如何尝试获取状态的。我实际上尝试了很多方法。做这些事情的最佳方式是什么?

我想在 Authenticator 结构中添加对所需数据的引用(例如 Arc'd RwLock),并在注册我的中间件时使用引用构建它。

我仍然不擅长 trait 的东西,但是必须有一种干净的方法将 S 类型转换为我的应用程序定义的 State 结构:

pub struct State {
    pub database: actix::Addr<actix::Syn, ::database::Actor>,
    pub cache: ::std::sync::Arc<::cache::Cache>,
    pub sessions: ::std::sync::Arc<::session::Storage>,
}

使用您的州而不是 S:

impl actix_web::middleware::Middleware<::Application::State> for Authenticator {
}

顺便说一下,中间件也可以有状态。