Como passar uma variável para actix-web guard () em Rust?
Sep 06 2020
#[actix_rt::main]
async fn main() -> std::io::Result<()> {
let token = env::var("TOKEN").expect("Set TOKEN");
HttpServer::new(|| {
App::new()
.wrap(middleware::Logger::default())
.service(
web::resource("/")
.guard(guard::Header("TOKEN", &token))
.route(web::post().to(index))
)
})
.bind("127.0.0.1:8080")?
.run()
.await
}
O erro é:
error[E0597]: `token` does not live long enough
Eu vi .data()nos documentos do actix, mas isso é para passar variáveis dentro de funções de rotas.
UPD:
Se eu adicionar "mover":
HttpServer::new(move || {
então apenas o erro muda:
error[E0495]: cannot infer an appropriate lifetime for borrow expression due to conflicting requirements
--> src/main.rs:50:58
|
50 | .guard(guard::Header("TOKEN", &token))
| ^^^^^^
|
note: first, the lifetime cannot outlive the lifetime `'_` as defined on the body at 42:21...
--> src/main.rs:42:21
|
42 | HttpServer::new(move || {
| ^^^^^^^
note: ...so that closure can access `token`
--> src/main.rs:50:58
|
50 | .guard(guard::Header("TOKEN", &token))
| ^^^^^^
= note: but, the lifetime must be valid for the static lifetime...
note: ...so that reference does not outlive borrowed content
--> src/main.rs:50:58
|
50 | .guard(guard::Header("TOKEN", &token))
| ^^^^^^
error: aborting due to previous error
Respostas
Sergey Sep 06 2020 at 19:41
actix-web cria muitos threads e cada trabalhador (em cada thread) deve obter uma cópia de uma variável. Então usando let token = token.clone();e move.
Depois disso, cada uma dessas variáveis entra em fn_guardfunção. Então mais uma vez move.
let token = env::var("TOKEN").expect("You must set TOKEN");
HttpServer::new(move || {
let token = token.clone();
App::new()
.wrap(middleware::Logger::default())
.service(
web::resource("/")
.guard(guard::fn_guard(
move |req| match req.headers().get("TOKEN") {
Some(value) => value == token.as_str(),
None => false,
}))
.route(web::post().to(index))
)
})
.bind("127.0.0.1:8080")?
.run()
.await
Isso funciona.
Não consigo trabalhar apenas com.guard(guard::Header("TOKEN", &token))
O que significa um erro “Não é possível encontrar o símbolo” ou “Não é possível resolver o símbolo”?
Christopher Nolan uma vez se arrependeu de ter lido o 'roteiro de Pulp Fiction' de Quentin Tarantino