gpt4 book ai didi

rust - 如何使用actix_web::guard::Header?

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

为了支持application/jsonmultipart/form-data在同一个 URL 上,我想检查“Content-Type” header 并选择合适的 Data<T>输入要提交给 .data App::new的功能.

如果我取消注释 .guard线,然后 curl -X POST -H "Content-Type: multipart/form-data" -F files=\"qqq\" localhost:8080/upload被丢弃。但是没有 .guard线路一切正常。怎么了?

HttpServer::new(move || {
App::new()
.service(resource("/upload")
// .guard(actix_web::guard::Header("Content-Type", "multipart/form-data"))
.data(form.clone())
.route(post()
.to(upload_multipart)
)
)
})

如何在一个App实例中正确加入它们?

最佳答案

目前,actix-web 1.0.3 does not support multipart/form-data , 但您可以使用 actix_multipart .由于重点是反序列化具有不同内容类型的相同数据,因此我简化为使用 application/x-www-form-urlencoded

要支持两种不同的内容类型,嵌套 web::resource 并为每个处理程序添加守卫:

web::resource("/")
.route(
web::post()
.guard(guard::Header(
"content-type",
"application/x-www-form-urlencoded",
))
.to(form_handler),
)
.route(
web::post()
.guard(guard::Header("content-type", "application/json"))
.to(json_handler),
),

创建接收反序列化数据的处理程序,并将数据发送到通用处理程序:

fn form_handler(user: web::Form<User>) -> String {
handler(user.into_inner())
}

fn json_handler(user: web::Json<User>) -> String {
handler(user.into_inner())
}

fn handler(user: User) -> String {
format!("Got username: {}", user.username)
}

结果:

$ curl -d 'username=adsf' localhost:8000
Got username: asdf⏎
$ curl -d '{"username": "asdf"}' localhost:8000
Parse error⏎
$ curl -d '{"username": "asdf"}' -H 'content-type: application/json' localhost:8000
Got username: asdf⏎

要创建自己的反序列化器,请实现 FromRequest特质。

关于rust - 如何使用actix_web::guard::Header?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56951776/

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