进阶 www.iris-go.com 2026-10-20 02:39:14 · 18 阅读

第51章 Iris 框架第51章:Markdown 响应

Markdown 响应 学习如何在 Iris 中提供 Markdown 内容。 基本 Markdown 响应 go package main import ( "github.com/kataras/iris/v12" "github.com/russross/blackfriday/v2" ) func main() { app := iris.New() app.Get("/markdown", func(ctx iris.Context) { markdown := []byte(` # Hello World This is a markdown document: * Item 1 * Item 2 * Item 3 `) html := blackfriday.Run(markdown) ctx.HTML(string(html)) }) app.Listen(":8080") } 1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
提供 Markdown 文件 go app.Get("/doc/{name}", func(ctx iris.Context) { name := ctx.Params().Get("name") content, err := os.ReadFile("./docs/" + name + ".md") if err != nil { ctx.StopWithError(iris.StatusNotFound, err) return } html := blackfriday.Run(content) ctx.HTML(string(html)) }) 1
2
3
4
5
6
7
8
9
10
11
自定义渲染 go func renderMarkdown(content []byte) []byte { extensions := blackfriday.WithExtensions( blackfriday.CommonExtensions | blackfriday.AutoHeadingIDs | blackfriday.NoEmptyLineBeforeBlock, ) return blackfriday.Run(content, extensions) } app.Get("/custom", func(ctx iris.Context) { content := []byte("# Custom Markdown") html := renderMarkdown(content) ctx.HTML(string(html)) }) 1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
最佳实践 安全: * 净化输入 * 验证内容 * 设置安全头 * 处理文件访问 * 监控使用情况 性能: * 缓存渲染内容 * 启用压缩 * 优化渲染 * 监控响应时间 * 处理超时 内容: * 验证 Markdown * 处理边缘情况 * 支持扩展 * 记录语法 * 定期更新 维护: * 监控错误 * 更新依赖 * 清理内容 * 记录变更 * 审查安全性

评论 (0)