A web blog and personal homepage engine written in Go.
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 

53 lines
1.3 KiB

package common
import (
"fmt"
"regexp"
"strings"
)
var (
// Regexp to locate relative URLs in HTML code.
reRelativeLink = regexp.MustCompile(` (src|href|poster)=(['"])/([^'"]+)['"]`)
// Regexp to detect common URL schemes.
reURLScheme = regexp.MustCompile(`^https?://`)
)
// ReplaceRelativeLinksToAbsolute searches an HTML snippet for relative links
// and replaces them with absolute ones using the given base URL.
func ReplaceRelativeLinksToAbsolute(baseURL string, html string) string {
if baseURL == "" {
return html
}
matches := reRelativeLink.FindAllStringSubmatch(html, -1)
for _, match := range matches {
var (
attr = match[1]
quote = match[2]
uri = match[3]
absURI = strings.TrimSuffix(baseURL, "/") + "/" + uri
replace = fmt.Sprintf(" %s%s%s%s",
attr, quote, absURI, quote,
)
)
html = strings.Replace(html, match[0], replace, 1)
}
return html
}
// ToAbsoluteURL converts a URL to an absolute one. If the URL is already
// absolute, it is returned as-is.
func ToAbsoluteURL(uri string, baseURL string) string {
match := reURLScheme.FindStringSubmatch(uri)
if len(match) > 0 {
return uri
}
if strings.HasPrefix(uri, "/") {
return strings.TrimSuffix(baseURL, "/") + uri
}
return strings.TrimSuffix(baseURL, "/") + "/" + uri
}