diff --git a/src/utils/links.go b/src/utils/links.go index 56ad79a..2044fa5 100644 --- a/src/utils/links.go +++ b/src/utils/links.go @@ -42,4 +42,20 @@ func ReplaceStackOverflowLinks(html string) string { // Replace the href attribute value in the anchor tag return strings.Replace(match, hrefMatch[1], newUrl, 1) }) -} \ No newline at end of file +} + +var relativeAnchorURLRegex = regexp.MustCompile(`href="(/[^"]+)"`) + +func ConvertRelativeAnchorURLsToAbsolute(html, prefix string) string { + if prefix == "" { + return html + } + + if !strings.HasSuffix(prefix, "/") { + prefix += "/" + } + + return relativeAnchorURLRegex.ReplaceAllStringFunc(html, func(match string) string { + return strings.Replace(match, "href=\"/", "href=\""+prefix, 1) + }) +} diff --git a/src/utils/links_test.go b/src/utils/links_test.go index 5279fe8..0c08209 100644 --- a/src/utils/links_test.go +++ b/src/utils/links_test.go @@ -2,9 +2,11 @@ package utils import ( "fmt" - "github.com/stretchr/testify/assert" + "log" "strings" "testing" + + "github.com/stretchr/testify/assert" ) var sampleInput = `
@@ -47,3 +49,42 @@ func TestReplaceStackOverflowLinks(t *testing.T) { assert.False(t, strings.Contains(replacedLinks, "stackoverflow.com")) assert.False(t, strings.Contains(replacedLinks, "stackexchange.com")) } + +var sampleRelativeAnchorURLsInput = ` +
+
+ Answered Sep 27, 2018 at 21:21 by + amon +
+
+` + +func TestConvertRelativeAnchorURLsToAbsolute(t *testing.T) { + prefix := "https://opensource.stackexchange.com" + fixedHTML := ConvertRelativeAnchorURLsToAbsolute(sampleRelativeAnchorURLsInput, prefix) + + log.Println(fixedHTML) + + assert.True(t, strings.Contains(fixedHTML, prefix)) + assert.True(t, strings.Contains(fixedHTML, "https://notopensource.stackexchange.com")) +}