Title here
Summary here
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:
Url::parse()
instead of url.Parse()
.expect()
or unwrap()
for simplicity.username()
and password()
methods.Host
, which we match against to handle different types of hosts.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.