rust - 在 actix-web 中用作查询参数时,如何将无效的枚举变体变为无
问题描述
使用文档中提供的示例,在提供未知变体时如何使用actix_web::web::Query
?response_type
None
如果我有以下情况:
use actix_web::{web, App, HttpServer};
use serde::Deserialize;
#[derive(Debug, Deserialize)]
pub enum ResponseType {
Token,
Code,
}
#[derive(Deserialize)]
pub struct AuthRequest {
id: u64,
response_type: Option<ResponseType>,
}
async fn index(web::Query(info): web::Query<AuthRequest>) -> String {
format!(
"Authorization request for client with id={} and type={:?}!",
info.id, info.response_type
)
}
#[actix_web::main]
async fn main() -> std::io::Result<()> {
HttpServer::new(|| App::new().route("/", web::get().to(index)))
.bind(("127.0.0.1", 8080))?
.run()
.await
}
我访问http://localhost:8080/?id=1&response_type=foo
,我得到这个 400 响应:
查询反序列化错误:未知变体
foo
,预期Token
或Code
当我希望它只接受 Enum 的值作为有效值时,如果没有提供值或无效值,我希望它设置为None
.
解决方案
这可以通过 deserialize_with 来处理。
use actix_web::{web, App, HttpServer};
use serde::Deserialize;
use serde::de::{Deserializer};
#[derive(Debug, Deserialize)]
pub enum ResponseType {
Token,
Code,
}
fn from_response_type<'de, D>(deserializer: D) -> Result<Option<ResponseType>, D::Error>
where
D: Deserializer<'de>,
{
let res: Option<ResponseType> = Deserialize::deserialize(deserializer).unwrap_or(None);
Ok(res)
}
#[derive(Debug, Deserialize)]
pub struct AuthRequest {
id: u64,
#[serde(deserialize_with = "from_response_type")]
response_type: Option<ResponseType>,
}
async fn index(web::Query(info): web::Query<AuthRequest>) -> String {
format!(
"Authorization request for client with id={} and type={:?}!",
info.id, info.response_type
)
}
#[actix_web::main]
async fn main() -> std::io::Result<()> {
HttpServer::new(|| App::new().route("/", web::get().to(index)))
.bind(("127.0.0.1", 8080))?
.run()
.await
}
任何无效值都被视为None
. 关键线是
let res: Option<ResponseType> = Deserialize::deserialize(deserializer).unwrap_or(None);
推荐阅读
- python - 在 Django Rest 框架中获取图像字段绝对路径 - 非请求流
- c# - WebDriverWait 不等待我指定的元素
- group-by - Group_by 仅返回一行,而聚合返回预期结果
- java - 更新和管理多个主屏幕小部件如何在 Java 中工作?
- javascript - 为什么 [[GetPrototypeOf]] 是 Javascript 代理的不变量?
- r - 如何表达 str_remove 的多条件?
- android - 具有可见性的下拉菜单项给我项目之间的空白
- c++ - 从文件中读取实部和虚部值并使用 C++ 中的复杂类形成一个复杂变量
- mongodb - 压缩两个数组并创建新的对象数组
- javascript - 酶按钮模拟无法按预期工作