MM-48089 Fix relative email urls

Этот коммит содержится в:
Maximilian Ripper
2023-01-17 18:21:32 +01:00
родитель 087aa38afb
Коммит 6020499a42
6 изменённых файлов: 58 добавлений и 17 удалений

Просмотреть файл

@@ -36,10 +36,17 @@ func StripMarkdown(markdown string) (string, error) {
}
// MarkdownToHTML takes a string containing Markdown and returns a string with HTML tagged version
func MarkdownToHTML(markdown string) (string, error) {
func MarkdownToHTML(markdown, siteURL string) (string, error) {
// Turn relative links into absolute links
relLinkRe := regexp.MustCompile(`\[(.*)]\((/.*)\)`)
absLinkMarkdown := relLinkRe.ReplaceAllFunc([]byte(markdown), func(s []byte) []byte {
out := relLinkRe.ReplaceAllString(string(s), "[$1]("+siteURL+"$2)")
return []byte(out)
})
// Unescape any blockquote text to be parsed by the markdown parser.
re := regexp.MustCompile(`^|\n(>)`)
markdownClean := re.ReplaceAllFunc([]byte(markdown), func(s []byte) []byte {
markdownClean := re.ReplaceAllFunc([]byte(absLinkMarkdown), func(s []byte) []byte {
out := html.UnescapeString(string(s))
return []byte(out)
})

Просмотреть файл

@@ -280,3 +280,37 @@ func TestStripMarkdown(t *testing.T) {
})
}
}
func TestMarkdownToHTML(t *testing.T) {
siteURL := "https://example.com"
tests := []struct {
name string
markdown string
want string
}{
{
name: "absolute url not changed",
markdown: "[Link](https://example.com)",
want: "<p><a href=\"https://example.com\">Link</a></p>\n",
},
{
name: "relative url changed to absolute url",
markdown: "[Link](/foo)",
want: "<p><a href=\"https://example.com/foo\">Link</a></p>\n",
},
{
name: "relative url with query params changed to absolute url",
markdown: "[Link](/foo?bar=true)",
want: "<p><a href=\"https://example.com/foo?bar=true\">Link</a></p>\n",
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
got, err := MarkdownToHTML(tt.markdown, siteURL)
if err != nil {
t.Fatalf("error: %v", err)
}
assert.Equal(t, tt.want, got)
})
}
}