From 9a759f09ffb267756d5d94caee05ee635e6d8bac Mon Sep 17 00:00:00 2001 From: Dominic Ferrando Date: Sat, 26 Apr 2025 13:31:47 -0400 Subject: [PATCH] Enrich links --- internal/util/posts.go | 29 ++++++++++++++++++----------- 1 file changed, 18 insertions(+), 11 deletions(-) diff --git a/internal/util/posts.go b/internal/util/posts.go index 0156744..768ba7f 100644 --- a/internal/util/posts.go +++ b/internal/util/posts.go @@ -12,6 +12,7 @@ import ( "os/exec" "path" "path/filepath" + "regexp" "slices" "strings" @@ -43,27 +44,33 @@ const ( PostFileUnsupported ) +var urlRx = regexp.MustCompile(`(?i)\bhttps?://[^\s<]+`) + func EnrichPost(body string) string { var b strings.Builder - for _, rawLine := range strings.Split(body, "\n") { - var outLine string - for i, rawWord := range strings.Split(rawLine, " ") { + for _, rawLine := range strings.Split(body, "\n") { + line := urlRx.ReplaceAllStringFunc(rawLine, func(u string) string { + esc := template.HTMLEscapeString(u) + return fmt.Sprintf( + `%[1]s`, + esc, + ) + }) + + var outLine string + for i, rawWord := range strings.Split(line, " ") { var outWord string if strings.HasPrefix(rawWord, ">>") { postId := strings.TrimPrefix(rawWord, ">>") - esc := template.HTMLEscapeString(rawWord) outWord = fmt.Sprintf( - `%s`, - postId, esc, + `%[2]s`, + postId, template.HTMLEscapeString(rawWord), ) } else { - outWord = template.HTMLEscapeString(rawWord) + outWord = rawWord } - if i != 0 { outLine += " " }