Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rust URL remove specific GET parameters

Tags:

url

rust

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 url crate doesn't seem to give me anything for this.

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

like image 612
Alex Avatar asked Oct 12 '25 06:10

Alex


2 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);
  }
like image 145
Günter Zöchbauer Avatar answered Oct 14 '25 21:10

Günter Zöchbauer


Remove all query parameters using .clear().

let url = Url::parse("http://blah.com/a/b?a=1&b=2").unwrap();
url.query_pairs_mut().clear();

Replacing query parameters.

let url = Url::parse("http://blah.com/a/b?a=1&b=2").unwrap();
let query = url
    .query_pairs()
    .filter(|(name, _)| name.ne("b"));
let mut url = url.clone();
url.query_pairs_mut()
    .clear()
    .extend_pairs(query)
    .extend_pairs([(Cow::from("new"), Cow::from("8"))]);

Rust Playground

like image 34
simanacci Avatar answered Oct 14 '25 21:10

simanacci