如何在 Actix-Web 中为多个方法使用路由属性宏

mat*_*thu 5 rust rust-actix actix-web

Actix Web Framework 中,如何使用路由属性宏 ( #[http_method("route")]) 将多个 http 方法绑定到一个函数?

例如,我有这个微不足道的端点:

/// Returns a UUID4.
#[get("/uuid")]
async fn uuid_v4() -> impl Responder {
    HttpResponse::Ok().json(Uuid {
        uuid: uuid::Uuid::new_v4(),
    })
}
Run Code Online (Sandbox Code Playgroud)

我想让相同的端点处理HEAD请求,我该怎么做? 我最初的方法是堆叠宏:

/// Returns a UUID4.
#[get("/uuid")]
#[head("/uuid")]
async fn uuid_v4() -> impl Responder {
    HttpResponse::Ok().json(Uuid {
        uuid: uuid::Uuid::new_v4(),
    })
}
Run Code Online (Sandbox Code Playgroud)

但我确实收到了编译错误:

    |
249 | async fn uuid_v4() -> impl Responder {
    |          ^^^^^^^ the trait `actix_web::handler::Factory<_, _, _>` is not implemented for `<uuid_v4 as actix_web::service::HttpServiceFactory>::register::uuid_v4`
Run Code Online (Sandbox Code Playgroud)

我已经通过了actix-webactix-web-codegen docs,并没有发现任何解决这一

tbo*_*iar 7

你可以做

#[route("/", method="GET", method="POST", method="PUT")]
async fn index() -> impl Responder {
  HttpResponse::Ok().body("Hello world!")
}

#[actix_web::main]
async fn main() -> std::io::Result<()> {
  HttpServer::new(move || {
    App::new()
        .service(index)
  })
  .bind("127.0.0.1:8080")?
  .run()
  .await
}
Run Code Online (Sandbox Code Playgroud)


Jbs*_*ice 5

一个资源的多个路径和多个方法的示例

async fn index() -> impl Responder {
  HttpResponse::Ok().body("Hello world!")
}

#[actix_web::main]
async fn main() -> std::io::Result<()> {
  HttpServer::new(move || {
    App::new()
        .service(
            actix_web::web::resource(vec!["/", "/index"])
                .route(actix_web::web::get().to(index))
                .route(actix_web::web::post().to(index))
            )
  })
  .bind("127.0.0.1:8080")?
  .run()
  .await
}
Run Code Online (Sandbox Code Playgroud)