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

rustsnippet
37 lines
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");
}

Inside the snippet

Count the functions encode_component, build_query and main as the entire surface area of Encode URL Query Parameters Correctly.

Repetition is confined to for byte in value.bytes() — the rest of the file is straight-line. Each possible shape of the input gets its own match arm, and the compiler checks the set is complete.

Putting it to use

Signature: fn encode_component(value: &str) -> String

main is the driver: it invokes build_query and encode_component before returning.

Core lines

.map(|(key, value)| format!("{}={}", encode_component(key), encode_component(value)))
.collect::<Vec<_>>()
.join("&")
}
b'A'..=b'Z' | b'a'..=b'z' | b'0'..=b'9' | b'-' | b'.' | b'_' | b'~' => {
encoded.push(byte as char);
}

Interactive Tools for This Topic

FAQ

How do you run Encode URL Query Parameters Correctly?
Nothing to install first — run the file and the program does the rest.