我有一个简单的中间件,用于访问应用程序的全局状态以执行身份验证令牌的验证:
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,
)),
}
}
}
注释后的字符串显示了我是如何尝试获取状态的。我实际上尝试了很多方法。做这些事的最好方法是什么?
我考虑过向Arc
结构添加对所需数据的引用(例如RwLock
'd Authenticator
),并在注册我的中间件时使用引用构建它。
我仍然不熟悉特质,但必须有一种简洁的方法将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>,
}
答案 0 :(得分:3)
使用您的州而不是S
:
impl actix_web::middleware::Middleware<::Application::State> for Authenticator {
}
顺便说一下,中间件也可以拥有状态。