LoginSignup
2
2

More than 3 years have passed since last update.

Rustでクエリパラメータを含むURLを生成したい時

Posted at

環境

  • rustc 1.43.0

やりたいこと

https://example.com?q=rust&order=asc みたいなURLのクエリ部分を動的に生成したい場合。

let url = format!("https://example.com?q={}&order={}", "rust", "desc");

このような文字列操作でもなんとかなるが、あまりイケてるとは言えないし、例えば q の値が空の場合は https://example.com?&order=asc みたいにキーごと含めないといった要件が出てくるとキツくなってくる。

urlクレート

というわけでurlクレートの Url::parse_with_params を使う。

Tuple

パラメータをタプルで渡す場合。

use url::Url;

fn main() {
    let tuples = vec![("q", "rust"), ("order", "desc")];
    let url = Url::parse_with_params("https://example.com", tuples).unwrap();
    println!("{}", url);  // output: https://example.com/?q=rust&order=desc
}

HashMap

HashMapで渡す場合。

use std::collections::HashMap;
use url::Url;

struct Params {
    q: String,
    order: String,
}

fn main() {
    let mut map = HashMap::new();
    map.insert("q", "rust");
    map.insert("order", "desc");
    let url = Url::parse_with_params("https://example.com", map).unwrap();
    println!("{}", url); // output: https://example.com/?q=rust&order=desc
}
2
2
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
2