fix: don't prepend if the prefix is already in the URL

This commit is contained in:
httpjamesm 2024-06-13 02:07:41 -04:00
parent 5b01a5c232
commit 71dec733b0
No known key found for this signature in database
2 changed files with 14 additions and 2 deletions

View file

@ -56,6 +56,16 @@ func ConvertRelativeAnchorURLsToAbsolute(html, prefix string) string {
} }
return relativeAnchorURLRegex.ReplaceAllStringFunc(html, func(match string) string { return relativeAnchorURLRegex.ReplaceAllStringFunc(html, func(match string) string {
return strings.Replace(match, "href=\"/", "href=\""+prefix, 1) // Extract the URL from the match
url := strings.TrimPrefix(match, `href="`)
url = strings.TrimSuffix(url, `"`)
// If the URL already has the desired prefix, return the match as is
if strings.HasPrefix(url, prefix) {
return match
}
// Otherwise, prepend the prefix
return strings.Replace(match, `href="/`, `href="`+prefix, 1)
}) })
} }

View file

@ -77,10 +77,12 @@ var sampleRelativeAnchorURLsInput = `<aside class="s-notice s-notice__info post-
<a href="https://notopensource.stackexchange.com/users/1212/amon" target="_blank" rel="noopener noreferrer">amon</a> <a href="https://notopensource.stackexchange.com/users/1212/amon" target="_blank" rel="noopener noreferrer">amon</a>
</div> </div>
</div> </div>
<a href="/exchange/opensource/9999/1111">This shouldn't be re-prefixed</a>
` `
func TestConvertRelativeAnchorURLsToAbsolute(t *testing.T) { func TestConvertRelativeAnchorURLsToAbsolute(t *testing.T) {
prefix := "https://opensource.stackexchange.com" prefix := "/exchange/opensource"
fixedHTML := ConvertRelativeAnchorURLsToAbsolute(sampleRelativeAnchorURLsInput, prefix) fixedHTML := ConvertRelativeAnchorURLsToAbsolute(sampleRelativeAnchorURLsInput, prefix)
log.Println(fixedHTML) log.Println(fixedHTML)