2013-10-01 15:59:29 -04:00
|
|
|
package transform
|
|
|
|
|
|
|
|
import (
|
2013-11-09 01:33:00 -05:00
|
|
|
"bytes"
|
2013-10-01 15:59:29 -04:00
|
|
|
htmltran "code.google.com/p/go-html-transform/html/transform"
|
|
|
|
"net/url"
|
2013-11-09 01:33:00 -05:00
|
|
|
"strings"
|
2013-10-01 15:59:29 -04:00
|
|
|
)
|
|
|
|
|
2013-11-05 17:28:06 -05:00
|
|
|
func AbsURL(absURL string) (trs []link, err error) {
|
2013-11-01 01:14:11 -04:00
|
|
|
var baseURL *url.URL
|
2013-10-01 15:59:29 -04:00
|
|
|
|
2013-11-01 01:14:11 -04:00
|
|
|
if baseURL, err = url.Parse(absURL); err != nil {
|
2013-10-01 15:59:29 -04:00
|
|
|
return
|
|
|
|
}
|
|
|
|
|
2013-11-09 01:33:00 -05:00
|
|
|
base := strings.TrimRight(baseURL.String(), "/")
|
|
|
|
|
2013-11-05 17:28:06 -05:00
|
|
|
var (
|
2013-11-09 01:33:00 -05:00
|
|
|
srcdq = []byte(" src=\"" + base + "/")
|
|
|
|
hrefdq = []byte(" href=\"" + base + "/")
|
|
|
|
srcsq = []byte(" src='" + base + "/")
|
|
|
|
hrefsq = []byte(" href='" + base + "/")
|
2013-11-05 17:28:06 -05:00
|
|
|
)
|
|
|
|
trs = append(trs, func(content []byte) []byte {
|
2013-11-09 09:35:09 -05:00
|
|
|
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)
|
2013-11-05 17:28:06 -05:00
|
|
|
return content
|
|
|
|
})
|
2013-11-01 01:14:11 -04:00
|
|
|
return
|
2013-10-01 15:59:29 -04:00
|
|
|
}
|
|
|
|
|
2013-11-09 09:35:09 -05:00
|
|
|
func guardReplace(content, guard, match, replace []byte) []byte {
|
2013-11-24 16:48:57 -05:00
|
|
|
if !bytes.Contains(content, guard) {
|
|
|
|
content = bytes.Replace(content, match, replace, -1)
|
|
|
|
}
|
|
|
|
return content
|
2013-11-09 09:35:09 -05:00
|
|
|
}
|
|
|
|
|
2013-10-01 15:59:29 -04:00
|
|
|
type elattr struct {
|
|
|
|
tag, attr string
|
|
|
|
}
|
|
|
|
|
2013-11-01 01:14:11 -04:00
|
|
|
func absUrlify(baseURL *url.URL, selectors ...elattr) (trs []*htmltran.Transform, err error) {
|
|
|
|
var inURL *url.URL
|
2013-10-01 15:59:29 -04:00
|
|
|
|
|
|
|
replace := func(in string) string {
|
|
|
|
if inURL, err = url.Parse(in); err != nil {
|
|
|
|
return in + "?"
|
|
|
|
}
|
|
|
|
if fragmentOnly(inURL) {
|
|
|
|
return in
|
|
|
|
}
|
|
|
|
return baseURL.ResolveReference(inURL).String()
|
|
|
|
}
|
|
|
|
|
|
|
|
for _, el := range selectors {
|
2013-11-01 01:14:11 -04:00
|
|
|
mt := htmltran.MustTrans(htmltran.TransformAttrib(el.attr, replace), el.tag)
|
|
|
|
trs = append(trs, mt)
|
2013-10-01 15:59:29 -04:00
|
|
|
}
|
|
|
|
|
|
|
|
return
|
|
|
|
}
|
|
|
|
|
|
|
|
func fragmentOnly(u *url.URL) bool {
|
|
|
|
return u.Fragment != "" && u.Scheme == "" && u.Opaque == "" && u.User == nil && u.Host == "" && u.Path == "" && u.Path == "" && u.RawQuery == ""
|
|
|
|
}
|