增加markdown支持。

This commit is contained in:
2026-07-28 15:51:54 +08:00
parent 98161a2fe8
commit 21be62fa7c
15 changed files with 353 additions and 6 deletions
+31
View File
@@ -0,0 +1,31 @@
package utils
import (
"bytes"
"html/template"
"github.com/yuin/goldmark"
"github.com/yuin/goldmark/extension"
goldmarkhtml "github.com/yuin/goldmark/renderer/html"
)
// markdownEngine 全局 Markdown 渲染引擎
// 启用 GFM 扩展(表格、删除线、任务列表、自动链接等)
// 启用 WithUnsafe 允许原始 HTML 透传,兼容旧文章中的 HTML 内容
var markdownEngine = goldmark.New(
goldmark.WithExtensions(extension.GFM),
goldmark.WithRendererOptions(
goldmarkhtml.WithUnsafe(),
goldmarkhtml.WithHardWraps(),
),
)
// RenderMarkdown 将 Markdown 文本渲染为 HTML
func RenderMarkdown(source string) template.HTML {
var buf bytes.Buffer
if err := markdownEngine.Convert([]byte(source), &buf); err != nil {
// 渲染失败时原样返回,避免页面空白
return template.HTML(source)
}
return template.HTML(buf.String())
}