为了支持application/json
和 multipart/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/