gpt4 book ai didi

rust - 如何在 actix_web 示例代码中提取变量?

转载 作者:行者123 更新时间:2023-11-29 08:17:24 24 4
gpt4 key购买 nike

这是主页上的 actix_web 示例代码:

use actix_web::{web, App, Responder, HttpServer};

fn index(info: web::Path<(String, u32)>) -> impl Responder {
format!("Hello {}! id:{}", info.0, info.1)
}

fn main() -> std::io::Result<()> {
HttpServer::new(|| App::new().service(
web::resource("/{name}/{id}/index.html").to(index))
)
.bind("127.0.0.1:8080")?
.run()
}

我试图通过为 web::resource... 行提取一个变量来重构代码:

use actix_web::{web, App, HttpServer, Responder};

fn index(info: web::Path<(u32, String)>) -> impl Responder {
format!("Hello {}! id:{}", info.1, info.0)
}

fn main() -> std::io::Result<()> {
let route = web::resource("/{id}/{name}/index.html").to(index);
HttpServer::new(|| App::new().service(route))
.bind("127.0.0.1:8080")?
.run()
}

但是编译失败。为什么失败了?以及如何在这里提取该变量?谢谢。

最佳答案

问题是服务需要在多线程环境中独占。通常你会克隆它,但正如你所注意到的,actix_web::resource::Resource 没有实现 std::clone::Clone。一种方法是自己实现这个特性并调用克隆。

一个更简单的解决方法是使用闭包:

fn main() -> std::io::Result<()> {
let route = || web::resource("/{id}/{name}/index.html").to(index);
HttpServer::new(move || {
App::new().service(route())
})
.bind("127.0.0.1:8080")?
.run()
}

你也可以选择 this方法,这可能是您要将变量提取到外部的原因。

关于rust - 如何在 actix_web 示例代码中提取变量?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58849546/

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