Rust URL remove specific GET parameters

Viewed 761

I have this URL as a String: "http://blah.com/a/b?a=1&b=2".

How can I remove or replace the GET parameter for b or strip the parameters entirely using Rust?

The ParseOptions of the rust-url package doesn't seem to give me anything for this.

Am I just limited to using String methods to find/replace?

1 Answers
let mut url = Url::parse("http://blah.com/a/b?a=1&b=2").unwrap();
url.set_query(None);

You can also take the query as pairs and manipulate it https://docs.rs/url/2.1.1/url/struct.Url.html#method.query_pairs_mut

Example how to update the query value for b (caution I'm a Rust beginner)

  use url::Url;
  fn main() {
      let url = Url::parse("http://blah.com/a/b?a=1&b=2").unwrap();
      let query: Vec<(_, _)> = url.query_pairs()
          .filter(|p| p.0 != "b")
          .collect();

      let mut url2 = url.clone();
      url2.set_query(None);

      for pair in query {
          url2.query_pairs_mut()
              .append_pair(&pair.0.to_string()[..], &pair.1.to_string()[..]);
      }
      url2.query_pairs_mut()
      .append_pair("b", "5");

      println!("New Query: {}", url2);
  }
Related