Last active
October 10, 2018 04:25
-
-
Save taylorza/e3d786f385f2f49c61ba2f332c0a10b5 to your computer and use it in GitHub Desktop.
Matches URL for a particular scheme and domain and replaces them with a new URL
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main | |
import ( | |
"net/url" | |
"regexp" | |
"strings" | |
) | |
// URLRewriter rewrites URL | |
type URLRewriter struct { | |
re *regexp.Regexp | |
newURL string | |
} | |
// NewURLRewriter creates an instance of a URLRewriter | |
func NewURLRewriter(oldURL, newURL string) (*URLRewriter, error) { | |
o, err := url.Parse(oldURL) | |
if err != nil { | |
return nil, err | |
} | |
n, err := url.Parse(newURL) | |
if err != nil { | |
return nil, err | |
} | |
r := &URLRewriter{} | |
// Create regex pattern to match old URL. | |
// The pattern purposely ingores the specified port and matches purely based on the scheme an hostname | |
pattern := `(?i)(` + o.Scheme + `://)?` + strings.Replace(o.Hostname(), `.`, `\.`, -1) + `:?\d*` | |
re, err := regexp.Compile(pattern) | |
if err != nil { | |
return nil, err | |
} | |
r.re = re | |
r.newURL = n.String() | |
return r, nil | |
} | |
// Rewrite rewrites the body with the replacement URL | |
func (r *URLRewriter) Rewrite(body string) string { | |
return r.re.ReplaceAllString(body, r.newURL) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment