// Copyright 2026 tamakyi. All rights reserved. // Use of this source code is governed by a MIT-style // license that can be found in the LICENSE file. package template import ( "html" "regexp" "strings" htmltemplate "html/template" ) // 公告正文里的 http(s) 地址自动变链接。 var announcementURLRe = regexp.MustCompile(`https?://[^\s<>"']+`) // 句末标点不属于 URL:中文公告里「详见 https://example.com/x。」很常见, // 不剥离就会把「。」一起链进去。 const announcementURLTailChars = ".,;:!?)]},。;:!?)】」”’" // AnnouncementHTML 把配置里的纯文本公告渲染成安全 HTML。 // // 按 URL 切段、逐段转义,而不是「先整体转义再正则」:转义后的 " 会被 URL // 字符类当成普通字符吞进链接。链接的 href 与可见文本共用同一份转义结果, // 因此不存在属性逃逸;内容里的 HTML 标签一律按字面显示。 func AnnouncementHTML(raw string) htmltemplate.HTML { raw = strings.ReplaceAll(raw, "\r\n", "\n") raw = strings.ReplaceAll(raw, `\r\n`, "\n") raw = strings.ReplaceAll(raw, `\n`, "\n") var b strings.Builder last := 0 for _, loc := range announcementURLRe.FindAllStringIndex(raw, -1) { url := raw[loc[0]:loc[1]] core := strings.TrimRight(url, announcementURLTailChars) tail := url[len(core):] b.WriteString(escapeAnnouncementText(raw[last:loc[0]])) escaped := html.EscapeString(core) b.WriteString(`` + escaped + ``) b.WriteString(escapeAnnouncementText(tail)) last = loc[1] } b.WriteString(escapeAnnouncementText(raw[last:])) return htmltemplate.HTML(b.String()) } func escapeAnnouncementText(s string) string { return strings.ReplaceAll(html.EscapeString(s), "\n", "
") }