Skip to content

Instantly share code, notes, and snippets.

@shakyShane
Created August 5, 2018 20:41
Show Gist options
  • Select an option

  • Save shakyShane/c6d507c31fc941b0211df981bb56c66b to your computer and use it in GitHub Desktop.

Select an option

Save shakyShane/c6d507c31fc941b0211df981bb56c66b to your computer and use it in GitHub Desktop.
pub fn replace_host<'a>(bytes: &'a str, host_to_replace: &'a str, target_host: &'a str, target_port: u16) -> Cow<'a, str> {
let matcher = format!("https?://{}", host_to_replace);
Regex::new(&matcher).unwrap().replace_all(bytes, |item: &Captures| main_replace(item, target_host, target_port))
}
fn main_replace(caps: &Captures, host: &str, port: u16) -> String {
caps.iter().nth(0)
.map_or(String::from(""),
// here there was a regex match
|capture_item| capture_item.map_or(String::from(""),
// here we have access to the individual match group
|item| {
// now we can try to parse the url
match Url::parse(item.as_str()) {
// if it parsed, we set the url to the value passed in
Ok(mut url) => {
match url.set_host(Some(host)) {
Ok(()) => match url.set_port(Some(port)) {
Ok(_) => {
println!("setting: {}", url.to_string());
url.to_string()
},
Err(_) => {
eprintln!("Could not set port");
String::from(item.as_str())
}
},
Err(_) => {
eprintln!("Could not set host");
String::from(item.as_str())
}
}
}
Err(_) => {
eprintln!("Could not parse url");
String::from(item.as_str())
}
}
}))
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment