Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to remove particular query from url in rust?

I’ve been trying to remove the particular query (ex: "remove=me") from the URL but it seems like there is no API for it

use url::{Url};

fn main(){
    let mut url = Url::parse("https://www.example.com/foo?id=1&remove=me").unwrap();
    url.set_query(None); // This will remove all the query parameters
    println!("{}", URL);

   // expected result: https://www.example.com/foo?id=1
   // actual result: https://www.example.com/foo
}

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Indeed, the url crate makes it quite awkward. The query string can only be appended to or cleared. Editing it requires some gymnastics: generating a filtered set of name/value pairs, then clearing and extended the query string.

let mut url = Url::parse("https://www.example.com/foo?id=1&remove=me").unwrap();

let query: Vec<(String, String)> = url
    .query_pairs()
    .filter(|(name, _)| name != "remove")
    .map(|(name, value)| (name.into_owned(), value.into_owned()))
    .collect();
url.query_pairs_mut().clear().extend_pairs(&query);

println!("{}", url);

Playground

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading