More efficient way to check for Url query parameter
⚓ Rust 📅 2025-09-12 👤 surdeus 👁️ 11I'm writing a web application with axum, and came up with the following to get a next_url query parameter from the current url (this is executed in the context of a handler, with the HeaderMap extractor), returning a default value of "/" in case REFERER header is unavailable, or the query key doesn't exist:
fn get_next_url(headers: HeaderMap) -> String {
let next_url = if let Some(referer_url) = headers
.get("REFERER")
.map(|x| x.to_str().ok())
.unwrap_or_else(|| None)
.map(|x| Url::from_str(x).ok())
.unwrap_or_else(|| None)
{
let query_map: HashMap<String, String> =
referer_url.query_pairs().into_owned().collect();
match query_map.get("next_url") {
Some(next_url) => next_url.clone(),
None => "/".to_string(),
}
} else {
"/".to_string()
};
next_url
}
This seems.. awfully verbose. I was hoping to do one long chain of maps and unwrap_or_elses, but got stuck on the temporary HashMap that had to be collected into, hence the match block.
Is there a better way of doing this?
Thanks!
4 posts - 3 participants
🏷️ Rust_feed