我想通过 from_request 实现 jwt,但是出现错误,提示
Send
未实现。然而,如果删除结构的特征实现,错误就会消失(即:impl CryptoService
)
use actix_web::{FromRequest, HttpResponse, ResponseError};
use actix_web::http::StatusCode;
use actix_web::web::Data;
use async_trait::async_trait;
use derive_more::Display;
use futures::future::BoxFuture;
pub struct CryptoService {}
#[async_trait(?Send)]
pub trait CryptoServiceAbstract {
async fn verify_jwt(&self);
}
#[async_trait(?Send)]
impl CryptoServiceAbstract for CryptoService {
async fn verify_jwt(&self) {
todo!()
}
}
#[derive(Debug, Display)]
pub struct ErrorReponse {}
impl ResponseError for ErrorReponse {
fn status_code(&self) -> StatusCode {
todo!()
}
fn error_response(&self) -> HttpResponse {
todo!()
}
}
pub struct AuthenticatedUser {}
impl FromRequest for AuthenticatedUser {
type Error = ErrorReponse;
type Future = BoxFuture<'static, Result<Self, Self::Error>>;
fn from_request(req: &actix_web::HttpRequest, payload: &mut actix_web::dev::Payload) -> Self::Future {
let crypto_service_result = Data::<CryptoService>::from_request(req, payload).into_inner();
match crypto_service_result {
Ok(crypto_service) => {
let future = async move {
crypto_service.verify_jwt().await;
Ok(AuthenticatedUser {})
};
Box::pin(future)
}
_ => {
todo!()
}
}
}
}
错误
error: future cannot be sent between threads safely
--> src\second_main.rs:53:17
|
53 | Box::pin(future)
| ^^^^^^^^^^^^^^^^ future created by async block is not `Send`
|
= help: the trait `std::marker::Send` is not implemented for `dyn futures::Future<Output = ()>`
note: future is not `Send` as it awaits another future which is not `Send`
--> src\second_main.rs:48:21
|
48 | crypto_service.verify_jwt().await;
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^ await occurs here on type `Pin<Box<dyn futures::Future<Output = ()>>>`, which is not `Send`
= note: required for the cast from `Pin<Box<{async block@src\second_main.rs:46:30: 51:18}>>` to `Pin<Box<dyn futures::Future<Output = Result<AuthenticatedUser, ErrorReponse>> + std::marker::Send>>`
[dependencies]
actix-web = "4.4.1"
derive_more = "0.99.17"
futures = "0.3.30"
async-trait = "0.1.77"
该错误是由于功能的实现导致的,我以为需要连接一些功能,但是我没有找到任何东西。我也删除了所有不需要的部分,但我仍然不明白问题可能出在哪里。
我通过将 Rust 版本从 1.74.1 更新到 1.75 解决了这个问题,这使得在特征中使用
async fn
成为可能。我仍然不明白为什么这对创建 async_trait 不起作用。但现在我放弃了使用这个板条箱,一切都正常了。
pub trait CryptoServiceAbstract {
async fn verify_jwt(&self);
}
impl CryptoServiceAbstract for CryptoService {
async fn verify_jwt(&self) {
todo!()
}
}