hugo/transform/absurl.go
2014-12-26 16:24:28 +01:00

64 lines
1.8 KiB
Go

package transform
import (
"bytes"
"net/url"
"strings"
)
func AbsURL(absURL string) (trs []link, err error) {
var baseURL *url.URL
if baseURL, err = url.Parse(absURL); err != nil {
return
}
base := strings.TrimRight(baseURL.String(), "/")
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
}
func AbsURLInXML(absURL string) (trs []link, err error) {
var baseURL *url.URL
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
}
func guardReplace(content, guard, match, replace []byte) []byte {
if !bytes.Contains(content, guard) {
content = bytes.Replace(content, match, replace, -1)
}
return content
}