Skip to content

Instantly share code, notes, and snippets.

@shakyShane
Created August 5, 2018 20:42
Show Gist options
  • Save shakyShane/4dfb51bec35afac19032cf1d635d760f to your computer and use it in GitHub Desktop.
Save shakyShane/4dfb51bec35afac19032cf1d635d760f to your computer and use it in GitHub Desktop.

Revisions

  1. shakyShane created this gist Aug 5, 2018.
    21 changes: 21 additions & 0 deletions rewrites.rs
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,21 @@
    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
    }
    }