Url Parsing in Rust

Here’s the translation of the URL parsing example from Go to Rust:

Our URL parsing program demonstrates how to parse and extract information from URLs in Rust.

use url::{Url, Host};

fn main() {
    // We'll parse this example URL, which includes a
    // scheme, authentication info, host, port, path,
    // query params, and query fragment.
    let s = "postgres://user:pass@host.com:5432/path?k=v#f";

    // Parse the URL and ensure there are no errors.
    let u = Url::parse(s).expect("Failed to parse URL");

    // Accessing the scheme is straightforward.
    println!("{}", u.scheme());

    // `username` and `password` methods provide authentication info.
    println!("{}:{}", u.username(), u.password().unwrap_or(""));

    // The `Host` enum contains hostname information.
    if let Some(host) = u.host() {
        match host {
            Host::Domain(h) => println!("{}", h),
            Host::Ipv4(h) => println!("{}", h),
            Host::Ipv6(h) => println!("{}", h),
        }
    }

    // Port can be accessed directly.
    println!("{}", u.port().unwrap_or(0));

    // Here we extract the path and the fragment after the #.
    println!("{}", u.path());
    println!("{}", u.fragment().unwrap_or(""));

    // To get query params in a string of k=v format, use `query`.
    // You can also parse query params into a map.
    println!("{}", u.query().unwrap_or(""));
    for (key, value) in u.query_pairs() {
        println!("{}={}", key, value);
    }
}

Running our URL parsing program shows all the different pieces that we extracted:

$ cargo run
postgres
user:pass
host.com
5432
/path
f
k=v
k=v

This Rust program uses the url crate to parse and manipulate URLs. Here’s a breakdown of the main differences from the Go version:

  1. We use Url::parse() instead of url.Parse().
  2. Error handling is done using expect() or unwrap() for simplicity.
  3. Authentication info is accessed via separate username() and password() methods.
  4. The host is represented as an enum Host, which we match against to handle different types of hosts.
  5. Query parameters are accessed using an iterator over key-value pairs.

The Rust version provides similar functionality to the Go version, with some differences in how the data is accessed and represented due to Rust’s type system and ownership model.