How to Parse a URL in Rust?

Parsing a URL in Rust is simple with the url crate. Here's a step-by-step guide on how to do it:

  1. Adding the url Crate to Your Project
[dependencies]
url = "2.2"
  1. Importing the url Crate
extern crate url;
use url::Url;
  1. Creating a Url Object
let url = Url::parse("https://example.com/path?name=value#hash").expect("Failed to parse URL");
  1. Accessing URL Components
println!("{}", url.scheme());    // Output: https
println!("{}", url.host_str().unwrap()); // Output: example.com
println!("{}", url.path());      // Output: /path
println!("{}", url.query().unwrap());    // Output: name=value
println!("{}", url.fragment().unwrap()); // Output: hash
  1. Working with URL Parameters
// Get a hashmap of URL parameters
let params: HashMap<String, String> = url.query_pairs()
    .into_owned()
    .collect();

println!("{:?}", params);  // Output: {"name" => "value"}
  1. Modifying and Reconstructing URLs
// Create a new URL with modified components
let new_url = url.join("/newpath").expect("Failed to join URL");

println!("{}", new_url);  // Output: https://example.com/newpath?name=value#hash

With the url crate, parsing a URL in Rust is straightforward, enabling you to access, analyze, and modify URLs with ease.

Lastly, if you want to grab query parameters from any url without using rust, use parseurlonline.com to quickly get the data without any hassle.