gpt4 book ai didi

rust - 如何在Rust中将变量传递给actix-web guard()?

转载 作者:行者123 更新时间:2023-12-03 11:39:22 26 4
gpt4 key购买 nike

#[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
}
错误是:
error[E0597]: `token` does not live long enough
我在actix文档中看到了 .data(),但这是用于在路由函数内部传递变量的。
UPD:
如果我添加“移动”:
HttpServer::new(move || {
然后只是错误更改:
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

最佳答案

actix-web创建了许多线程,并且每个工作人员(在每个线程中)必须获取变量的副本。因此,使用let token = token.clone();move
之后,这些变量中的每一个都进入fn_guard函数。因此,再次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
这行得通。
仅使用 .guard(guard::Header("TOKEN", &token))无法使其工作

关于rust - 如何在Rust中将变量传递给actix-web guard()?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63758122/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com