解析 Rust 中请求的查询参数。

huangapple go评论118阅读模式
英文:

parse query parameters from request in rust

问题

我第一次使用Rust,尝试解析HTTP请求中的查询参数。假设请求的URL是http://someUrl.com?param1=123&param2=345,我试图捕获123和345。

英文:

I'm using rust for the first time and i'm trying to parse query parameters from a http request. Lets say the request url is http://someUrl.com?param1=123&param2=345
I'm trying to capture 123 and 345

答案1

得分: 3

如果你正在处理 Web 服务器的请求,你使用的 Web 服务器库肯定有自己的处理方式。

如果你只需要解析 URL 中的查询参数,你可以使用 url 库来实现:

  1. use url::Url; // v2.3.1
  2. fn main() {
  3. let url = Url::try_from("http://someUrl.com?param1=123&param2=345").unwrap();
  4. for (key, val) in url.query_pairs() {
  5. println!("{key} = {val}");
  6. }
  7. }

这里的变量都是字符串。

更可能的情况是,你希望将这些变量反序列化为方便的类型。你可以使用 serdeserde_qs 来实现:

  1. use serde::Deserialize;
  2. use url::Url;
  3. #[derive(Deserialize, Debug)]
  4. struct MyQuery {
  5. param1: usize,
  6. param2: i32,
  7. }
  8. fn main() {
  9. let url = Url::try_from("http://someUrl.com?param1=123&param2=345").unwrap();
  10. if let Some(query) = url.query() {
  11. let my_query: MyQuery = serde_qs::from_str(query).unwrap();
  12. println!("{my_query:?}");
  13. }
  14. }
英文:

If you are handling a request in a web server, the web server crate that you are using will certainly have its own way to do this.

If you just need to parse query parameters from a URL, you can do that using url:

  1. use url::Url; // v2.3.1
  2. fn main() {
  3. let url = Url::try_from("http://someUrl.com?param1=123&param2=345").unwrap();
  4. for (key, val) in url.query_pairs() {
  5. println!("{key} = {val}");
  6. }
  7. }

Here the variables are all strings.

More likely, you'll want to deserialize the variables into convenient types. You can do that with serde and serde_qs:

  1. use serde::Deserialize;
  2. use url::Url;
  3. #[derive(Deserialize, Debug)]
  4. struct MyQuery {
  5. param1: usize,
  6. param2: i32,
  7. }
  8. fn main() {
  9. let url = Url::try_from("http://someUrl.com?param1=123&param2=345").unwrap();
  10. if let Some(query) = url.query() {
  11. let my_query: MyQuery = serde_qs::from_str(query).unwrap();
  12. println!("{my_query:?}");
  13. }
  14. }

huangapple
  • 本文由 发表于 2023年3月4日 04:29:43
  • 转载请务必保留本文链接:https://go.coder-hub.com/75631614.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定