fix(web): preserve absolute URLs in card hrefs

News and other cards with http(s) or root-relative links were incorrectly prefixed with link_prefix, breaking SSR /news.

Co-authored-by: Cursor <cursoragent@cursor.com>
This commit is contained in:
cflmyandCursor committed 2026-09-18 11:03:15 +08:00
1 parent bfea2204eb
commit 5f07b1c3b1
2 files changed
+39 -6

No files matched your search

+22 -6
View File
@@ -770,10 +770,30 @@ func headHTML(page map[string]any, defaultTitle string) string {
return s.String()
}
func cardHref(page map[string]any, href string) string {
href = strings.TrimSpace(href)
if href == "" {
return ""
}
if strings.HasPrefix(href, "http://") || strings.HasPrefix(href, "https://") || strings.HasPrefix(href, "//") {
return href
}
if strings.HasPrefix(href, "/") {
return href
}
prefix := "/post/"
if page != nil {
if p, ok := page["link_prefix"].(string); ok {
prefix = p
}
}
return prefix + href
}
func renderCard(page map[string]any, it map[string]any) string {
title := text(it["title"])
body := text(it["body"])
href := text(it["href"])
href := cardHref(page, text(it["href"]))
meta := text(it["meta"])
tag := text(it["tag"])
tc := classAttr(fieldCSS(it, "title"))
@@ -781,11 +801,7 @@ func renderCard(page map[string]any, it map[string]any) string {
var card strings.Builder
card.WriteString(`<article class="card">`)
if href != "" {
prefix := "/post/"
if p, ok := page["link_prefix"].(string); ok {
prefix = p
}
card.WriteString(fmt.Sprintf(`<a class="card-link" href="%s">`, esc(prefix+href)))
card.WriteString(fmt.Sprintf(`<a class="card-link" href="%s">`, esc(href)))
}
if meta != "" {
card.WriteString(fmt.Sprintf(`<div class="card-meta">%s</div>`, esc(meta)))
@@ -103,3 +103,20 @@ func TestMarkdownToHTML(t *testing.T) {
t.Fatalf("%s", out)
}
}
func TestCardHrefAbsoluteAndPrefixed(t *testing.T) {
page := map[string]any{"link_prefix": "/post/"}
if got := cardHref(page, "https://example.com/a"); got != "https://example.com/a" {
t.Fatalf("absolute: %q", got)
}
if got := cardHref(page, "/about"); got != "/about" {
t.Fatalf("root: %q", got)
}
if got := cardHref(page, "hello"); got != "/post/hello" {
t.Fatalf("prefixed: %q", got)
}
html := renderCard(page, map[string]any{"title": "T", "href": "https://ex.test/x", "body": "b"})
if !strings.Contains(html, `href="https://ex.test/x"`) {
t.Fatalf("card absolute: %s", html)
}
}