diff options
Diffstat (limited to 'transform/absurl.go')
-rw-r--r-- | transform/absurl.go | 59 |
1 files changed, 14 insertions, 45 deletions
diff --git a/transform/absurl.go b/transform/absurl.go index 0a0cd7239..0efe624ac 100644 --- a/transform/absurl.go +++ b/transform/absurl.go @@ -1,64 +1,33 @@ package transform import ( - "bytes" - "net/url" - "strings" + "sync" ) -func AbsURL(absURL string) (trs []link, err error) { - var baseURL *url.URL +var absUrlInit sync.Once +var ar *absurlReplacer - if baseURL, err = url.Parse(absURL); err != nil { - return - } +// for performance reasons, we reuse the first baseUrl given +func initAbsurlReplacer(baseURL string) { + absUrlInit.Do(func() { + ar = newAbsurlReplacer(baseURL) + }) +} - base := strings.TrimRight(baseURL.String(), "/") +func AbsURL(absURL string) (trs []link, err error) { + initAbsurlReplacer(absURL) - var ( - srcdq = []byte(" src=\"" + base + "/") - hrefdq = []byte(" href=\"" + base + "/") - srcsq = []byte(" src='" + base + "/") - hrefsq = []byte(" href='" + base + "/") - ) trs = append(trs, func(content []byte) []byte { - content = guardReplace(content, []byte(" src=\"//"), []byte(" src=\"/"), srcdq) - content = guardReplace(content, []byte(" src='//"), []byte(" src='/"), srcsq) - content = guardReplace(content, []byte(" href=\"//"), []byte(" href=\"/"), hrefdq) - content = guardReplace(content, []byte(" href='//"), []byte(" href='/"), hrefsq) - return content + return ar.replaceInHtml(content) }) return } func AbsURLInXML(absURL string) (trs []link, err error) { - var baseURL *url.URL + initAbsurlReplacer(absURL) - if baseURL, err = url.Parse(absURL); err != nil { - return - } - - base := strings.TrimRight(baseURL.String(), "/") - - var ( - srcedq = []byte(" src="" + base + "/") - hrefedq = []byte(" href="" + base + "/") - srcesq = []byte(" src='" + base + "/") - hrefesq = []byte(" href='" + base + "/") - ) trs = append(trs, func(content []byte) []byte { - content = guardReplace(content, []byte(" src="//"), []byte(" src="/"), srcedq) - content = guardReplace(content, []byte(" src='//"), []byte(" src='/"), srcesq) - content = guardReplace(content, []byte(" href="//"), []byte(" href="/"), hrefedq) - content = guardReplace(content, []byte(" href='//"), []byte(" href='/"), hrefesq) - return content + return ar.replaceInXml(content) }) return } - -func guardReplace(content, guard, match, replace []byte) []byte { - if !bytes.Contains(content, guard) { - content = bytes.Replace(content, match, replace, -1) - } - return content -} |