Fix URL parameter


At first I tried some over-engineered solutions, till I got the recommendation to use trim_end_matches.


examples/other/fix-url-string/src/main.rs
fn main() {
    for url in [
        String::from("https://rust.code-maven.com"),
        String::from("https://rust.code-maven.com/"),
    ] {
        process_rec(&url);
        process_mut(&url);
        pre_process(&url);
        trim_if_needed(&url);
    }
}

fn trim_if_needed(url: &str) {
    process(url.trim_end_matches('/'));
}

fn process_rec(url: &str) {
    if url.ends_with('/') {
        return process_rec(&url[0..url.len() - 1]);
    }
    process(url);
}

fn process_mut(mut url: &str) {
    if url.ends_with('/') {
        url = &url[0..url.len() - 1];
    }
    process(url);
}

fn pre_process(url: &str) {
    if url.ends_with('/') {
        return process(&url[0..url.len() - 1]);
    }
    process(url)
}

fn process(url: &str) {
    fetch(url);
    fetch(&format!("{}/page", url));
}

fn fetch(url: &str) {
    println!("Process '{}'", url);
}

However using the url crate might be the best solution in this case:


examples/other/fix-url/Cargo.toml
[package]
name = "fix-url"
version = "0.1.0"
edition = "2021"

# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html

[dependencies]
url = "2.5.0"

examples/other/fix-url/src/main.rs
fn main() {
    for site in [
        String::from("https://rust.code-maven.com"),
        String::from("https://rust.code-maven.com/"),
    ] {
        process(url::Url::parse(&site).unwrap());
    }
}

fn process(site: url::Url) {
    fetch(&site);
    fetch(&site.join("page").unwrap());
}

fn fetch(site: &url::Url) {
    println!("Process '{}'", site);
}