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

时间:2019-11-14 04:46:11

标签: rust actix-web

以下是其主页上的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()
}

但是无法编译。为什么失败了?以及如何在此处提取该变量?谢谢。

1 个答案:

答案 0 :(得分:1)

问题是该服务需要在多线程环境中具有排他所有权。通常,您只是克隆它,但是正如您所注意到的,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方法,这可能就是您要将变量提取到外部的原因。