gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-03 11:25:47 36 4
gpt4 key购买 nike

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

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

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

我想拥有相同的端点句柄 HEAD请求, 我该怎么做呢?
我最初的方法是堆叠宏:

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

但我确实得到了一个编译错误:
    |
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`

我已经通过 actix-webactix-web-codegen docs并没有找到任何解决这个问题的方法

最佳答案

你可以做

#[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
}

关于rust - 如何在 Actix-Web 中为多种方法使用路由属性宏,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60309300/

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