如何使用actix-web解析来自以下网址的name和color参数
http://example.com/path/to/page?name=ferret&color=purple我假设我的路径应该是/path/to/page,然后当我尝试查询name时,我收到一个空字符串(req.match_info().query("name") where req: &HttpRequest)。
我找到的唯一documentation是关于匹配名称的(例如,如果路径是/people/{page}/,它将匹配/people/123/,这样page = 123就不是我想要的。
发布于 2019-09-23 11:30:02
看起来他们去掉了query函数,只有一个query_string函数。您可以为此使用一个名为qstring的板条箱
use qstring::QString;
...
let query_str = req.query_string(); // "name=ferret"
let qs = QString::from(query_str);
let name = qs.get("name").unwrap(); // "ferret"您还可以使用extractor将查询参数反序列化为带有Serde的结构
use serde::Deserialize;
#[derive(Deserialize)]
struct Info {
username: String,
}
fn index(info: web::Query<Info>) -> Result<String, actix_web::Error> {
Ok(format!("Welcome {}!", info.username))
}请注意,只有当查询username实际出现在请求中时,才会调用处理程序。这将调用处理程序:
curl "http://localhost:5000?username=joe"
但这些不会:
curl "http://localhost:5000"
curl "http://localhost:5000?password=blah"如果你需要可选的参数,只需在你的结构中设置Option属性即可。
username: Option<String>您还可以在一个处理程序中使用多个web::Query<SomeType>参数。
发布于 2019-01-29 00:22:42
这是针对actix-web v0.7的
通过使用以下命令,我设法让它正常工作:
let name = req.query().get("name").unwrap(); // name = "ferret"发布于 2021-07-14 20:06:48
actix_web::web::query解析查询字符串:
use actix_web::{web, App};
use serde_derive::Deserialize;
#[derive(Debug, Deserialize)]
pub struct Params {
name: String,
color: String,
}
#[get("/path/to/page")]
async fn handler(req: HttpRequest) -> HttpResponse {
let params = web::Query::<Params>::from_query(req.query_string()).unwrap();
HttpResponse::Ok().body(format!("{:?}", params))
}The official documentation有另一个例子。
https://stackoverflow.com/questions/54406029
复制相似问题