
go 语言的 html/template 包在设计时,将安全性放在了首位。为了防止跨站脚本攻击(xss)等常见的 web 安全漏洞,它默认会对所有通过管道(pipeline)插入到 html 模板中的数据进行自动转义。这意味着,如果你的数据中包含 <、>、& 等 html 特殊字符,它们会被转换为对应的 html 实体(如 、&)。
在提供的示例中,从 RSS feed 获取的 Description 字段本身包含 HTML 结构(例如 <table> 标签),但当它被 {{.Description}} 渲染到页面时,这些 HTML 标签被转义,导致它们作为纯文本而不是实际的 HTML 元素显示在页面上。
当开发者明确知道某些字符串内容是安全且合法的 HTML,并且希望模板引擎直接将其渲染而不进行转义时,可以使用 html/template 包提供的 template.HTML 类型。
template.HTML 是一个字符串别名类型。当 html/template 遇到这个类型的值时,它会信任该内容,并将其直接插入到输出中,而不会执行任何转义操作。
为了解决 Description 字段被转义的问题,我们需要对数据结构和数据处理逻辑进行调整。
立即学习“前端免费学习笔记(深入)”;
首先,定义一个用于 XML 解码的临时结构,其中 Description 字段仍为 string 类型,因为 encoding/xml 包无法直接将 XML 内容解码为 template.HTML。然后,在将数据传递给模板之前,遍历数据列表,将 Description 字段显式转换为 template.HTML 类型。
package main
import (
"encoding/xml"
"fmt"
"html/template" // 导入 html/template 包
"io/ioutil"
"log"
"net/http"
)
// RSS 结构体,用于XML解码
type RSS struct {
XMLName xml.Name `xml:"rss"`
Channel RSSChannel `xml:"channel"`
}
// RSSChannel 结构体
type RSSChannel struct {
XMLName xml.Name `xml:"channel"`
ItemList []RSSItem `xml:"item"`
}
// RSSItem 结构体,用于XML解码,Description 仍为 string
type RSSItem struct {
Title string `xml:"title"`
Link string `xml:"link"`
Description string `xml:"description"`
}
// TemplateData 结构体,用于传递给模板,Description 为 template.HTML
type TemplateItem struct {
Title string
Link string
Description template.HTML // 关键:将 Description 定义为 template.HTML
}
type TemplateChannel struct {
ItemList []TemplateItem
}
func main() {
res, err := http.Get("http://news.google.com/news?hl=en&gl=us&q=samsung&um=1&ie=UTF-8&output=rss")
if err != nil {
log.Fatal(err)
}
defer res.Body.Close() // 确保关闭响应体
asText, err := ioutil.ReadAll(res.Body)
if err != nil {
log.Fatal(err)
}
var rssData RSS
err = xml.Unmarshal([]byte(asText), &rssData)
if err != nil {
log.Fatal(err)
}
// 将解码后的 RSSItem 转换为 TemplateItem,并处理 Description 字段
var templateChannel TemplateChannel
for _, item := range rssData.Channel.ItemList {
templateChannel.ItemList = append(templateChannel.ItemList, TemplateItem{
Title: item.Title,
Link: item.Link,
Description: template.HTML(item.Description), // 显式转换为 template.HTML
})
}
http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
handler(w, r, templateChannel) // 传递转换后的数据
})
fmt.Println("Server listening on :8080...")
log.Fatal(http.ListenAndServe(":8080", nil))
}
func handler(w http.ResponseWriter, r *http.Request, data TemplateChannel) {
// 解析模板文件
t, err := template.ParseFiles("index.html")
if err != nil {
http.Error(w, "Error parsing template: "+err.Error(), http.StatusInternalServerError)
return
}
// 执行模板,传入 TemplateChannel 数据
err = t.Execute(w, data)
if err != nil {
http.Error(w, "Error executing template: "+err.Error(), http.StatusInternalServerError)
return
}
}HTML 模板文件保持不变,因为 template.HTML 类型的数据在模板中引用时会自动被识别并渲染。
<html>
<head>
<title>Go RSS Feed</title>
<style>
body { font-family: Arial, sans-serif; margin: 20px; }
.news-item { border: 1px solid #eee; padding: 15px; margin-bottom: 10px; background-color: #f9f9f9; }
.news-item p { margin: 5px 0; }
.news-item a { text-decoration: none; color: #007bff; }
.news-item a:hover { text-decoration: underline; }
</style>
</head>
<body>
<h1>最新新闻</h1>
{{range .ItemList}}
<div class="news-item">
<p>
<a href="{{.Link}}">{{.Title}}</a>
</p>
<p>{{.Description}}</p> <!-- 此处 Description 将被渲染为未转义的 HTML -->
</div>
{{end}}
</body>
</html>通过上述修改,当 handler 函数执行 t.Execute(w, data) 时,data 中的 TemplateItem.Description 字段因为是 template.HTML 类型,其内容将作为原始 HTML 直接插入到输出中,而不再被转义。
尽管 template.HTML 提供了渲染原始 HTML 的能力,但使用时必须极其谨慎,因为它会绕过 html/template 的安全防护机制。
html/template 包通过默认的 HTML 转义机制提供了强大的安全保障。当确实需要渲染原始 HTML 内容时,template.HTML 类型提供了一个明确的接口来指示模板引擎信任并直接输出这些内容。然而,使用此特性意味着开发者需要承担相应的安全责任,务必确保所有通过 template.HTML 渲染的内容都经过严格的来源验证或净化处理,以防止潜在的 Web 安全漏洞。正确地运用 template.HTML,可以在保证应用安全性的前提下,实现灵活且丰富的页面展示效果。
以上就是Go HTML 模板中安全渲染未转义 HTML 内容的指南的详细内容,更多请关注php中文网其它相关文章!
HTML怎么学习?HTML怎么入门?HTML在哪学?HTML怎么学才快?不用担心,这里为大家提供了HTML速学教程(入门课程),有需要的小伙伴保存下载就能学习啦!
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号