Encode URL Query Parameters Correctly
Percent-encode URL query keys and values as UTF-8, preserving unreserved characters and encoding spaces as %20.
Code
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
Base64url CodecEncode and decode Base64url, the URL- and filename-safe variant that swaps + and / for - and _ and omits padding.Query String ParserParse a query string or URL into decoded key-value rows, preserving repeated keys and empty values for debugging and API work.URL Encoder & DecoderEncode and decode URLs and their components safely. Switch between encodeURIComponent and encodeURI modes to handle query parameters, paths, and special characters.URL Query String SerializerParse a URL query string into decoded key/value pairs or serialize key=value lines into a percent-encoded query string with duplicate-key detection.
FAQ
- How do you run Encode URL Query Parameters Correctly?
- Nothing to install first — run the file and the program does the rest.
Report a problem with this exampleOpens a pre-filled issue on GitHub.