mirror of
https://github.com/httpjamesm/AnonymousOverflow.git
synced 2025-04-23 23:39:16 +00:00
fix: don't prepend if the prefix is already in the URL
This commit is contained in:
parent
5b01a5c232
commit
71dec733b0
2 changed files with 14 additions and 2 deletions
|
@ -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)
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
|
@ -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)
|
||||||
|
|
Loading…
Add table
Reference in a new issue