Skip to content

Instantly share code, notes, and snippets.

@shakyShane
Created August 5, 2018 20:42
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save shakyShane/4dfb51bec35afac19032cf1d635d760f to your computer and use it in GitHub Desktop.
Save shakyShane/4dfb51bec35afac19032cf1d635d760f 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|
modify_url(item, target_host, target_port).unwrap_or(String::from("")))
}
fn modify_url(caps: &Captures, host: &str, port: u16) -> Option<String> {
let first_match = caps.iter().nth(0)?;
let match_item = first_match?;
if let Ok(mut url) = Url::parse(match_item.as_str()) {
url.set_host(Some(host)).ok();
url.set_port(Some(port)).ok();
Some(url.to_string())
} else {
None
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment