Encode URL Query Parameters Correctly

Percent-encode URL query keys and values as UTF-8, preserving unreserved characters and encoding spaces as %20.

RustData Fetching

Code

snippet
fn encode_component(value: &str) -> String {
    let mut encoded = String::new();
    for byte in value.bytes() {
        match byte {
            b'A'..=b'Z' | b'a'..=b'z' | b'0'..=b'9' | b'-' | b'.' | b'_' | b'~' => {
                encoded.push(byte as char);
            }
            b' ' => encoded.push_str("%20"),
            _ => encoded.push_str(&format!("%{byte:02X}")),
        }
    }
    encoded
}

fn build_query(parameters: &[(&str, &str)]) -> String {
    parameters
        .iter()
        .map(|(key, value)| format!("{}={}", encode_component(key), encode_component(value)))
        .collect::<Vec<_>>()
        .join("&")
}

fn main() {
    let query = build_query(&[
        ("q", "rust & go"),
        ("tag", "a+b"),
        ("path", "/docs/start"),
        ("empty", ""),
    ]);
    println!("{query}");
    assert_eq!(
        query,
        "q=rust%20%26%20go&tag=a%2Bb&path=%2Fdocs%2Fstart&empty="
    );
    assert_eq!(encode_component("café"), "caf%C3%A9");
}