html/template

最後更新


html/template 用來產生 HTML:範本語法和 text/template 相同,但會依照插入位置自動跳脫資料,防止 XSS 攻擊。

這個套件做什麼


網頁常把使用者輸入的內容(留言、暱稱、搜尋字)放進 HTML。如果有人把暱稱設成 <script>alert(1)</script>,直接輸出就會在其他人的瀏覽器執行這段程式,這種攻擊叫跨站腳本攻擊(XSS,Cross-Site Scripting)。
html/template 的做法是「情境感知跳脫」(contextual autoescaping):它在解析範本時理解 HTML 結構,知道每個 {{ }} 落在一般文字、屬性值、URL、JavaScript 或 CSS 裡,再對資料套用該位置正確的跳脫方式。你不用手動呼叫跳脫函式,預設就是安全的。
和 text/template 的關係:
text/templatehtml/template
範本語法相同相同
自動跳脫無依 HTML 情境跳脫
適用輸出設定檔、程式碼、純文字HTML 網頁、HTML Email

範本語法({{.Field}}、if、range、define、FuncMap)的詳細說明見 text/template,本頁專注在 HTML 特有的行為。

匯入


  1. import "html/template"

同一個檔案不要同時匯入兩個 template 套件;如果真的需要,替其中一個取別名。

常用 API


New、Parse 與 Execute(自動跳脫)


用法和 text/template 一樣。差別在輸出:資料中的 <、>、&、"、' 會被轉成 HTML 實體(entity),例如 < 變成 &lt;,瀏覽器只會把它顯示成文字,不會當成標籤。
簽名:
  1. func New(name string) *Template
  2. func (t *Template) Parse(text string) (*Template, error)
  3. func (t *Template) Execute(wr io.Writer, data any) error
  4. func Must(t *Template, err error) *Template

範例:
  1. package main
  2. import (
  3. "fmt"
  4. "html/template"
  5. "os"
  6. )
  7. type Comment struct {
  8. Author string
  9. Body string
  10. }
  11. func main() {
  12. t := template.Must(template.New("c").Parse(`<div class="comment"><b>{{.Author}}</b>: {{.Body}}</div>
  13. `))
  14. c := Comment{
  15. Author: "Mallory",
  16. Body: `<script>alert("hi")</script> & bye`,
  17. }
  18. if err := t.Execute(os.Stdout, c); err != nil {
  19. fmt.Println(err)
  20. }
  21. }

輸出:
  1. <div class="comment"><b>Mallory</b>: &lt;script&gt;alert(&#34;hi&#34;)&lt;/script&gt; &amp; bye</div>

情境感知跳脫


同一份資料放在不同位置,跳脫方式也不同:
  • HTML 文字中:轉成 HTML 實體
  • 屬性值中:轉成 HTML 實體,連引號也會處理
  • href、src 這類 URL 屬性:先檢查網址協定,javascript: 這類危險網址會被換成 #ZgotmplZ,再做 URL 編碼
  • <script> 中:轉成 JavaScript 值(字串會加上引號並跳脫)

#ZgotmplZ 是一個刻意的記號,看到它代表「有不安全的值被擋下來了」。
範例:
  1. package main
  2. import (
  3. "fmt"
  4. "html/template"
  5. "os"
  6. )
  7. func main() {
  8. const page = `<a href="/search?q={{.Query}}" title="{{.Query}}">{{.Query}}</a>
  9. <a href="{{.Link}}">link</a>
  10. <script>var q = {{.Query}};</script>
  11. `
  12. t := template.Must(template.New("p").Parse(page))
  13. data := map[string]string{
  14. "Query": `go & "rust"`,
  15. "Link": "javascript:alert(1)",
  16. }
  17. if err := t.Execute(os.Stdout, data); err != nil {
  18. fmt.Println(err)
  19. }
  20. }

輸出:
  1. <a href="/search?q=go%20%26%20%22rust%22" title="go &amp; &#34;rust&#34;">go &amp; &#34;rust&#34;</a>
  2. <a href="#ZgotmplZ">link</a>
  3. <script>var q = "go \u0026 \"rust\"";</script>

template.HTML 等信任型別


有時資料本身就是可信任的 HTML,例如由程式產生、已經清理過的 Markdown 轉換結果,不希望被跳脫。這時把字串轉成 template.HTML,範本會原樣輸出。同類的型別還有 template.URL、template.JS、template.CSS、template.HTMLAttr。
注意:這些型別等於告訴套件「我保證這段內容安全」,跳過了所有保護。絕對不要把使用者輸入直接轉成 template.HTML,否則等於自己打開 XSS 漏洞。
簽名:
  1. type HTML string
  2. type URL string
  3. type JS string

範例:
  1. package main
  2. import (
  3. "fmt"
  4. "html/template"
  5. "os"
  6. )
  7. func main() {
  8. t := template.Must(template.New("t").Parse(`plain: {{.Plain}}
  9. trusted: {{.Trusted}}
  10. <a href="{{.Link}}">tel</a>
  11. `))
  12. data := map[string]any{
  13. "Plain": "<em>hello</em>",
  14. "Trusted": template.HTML("<em>hello</em>"),
  15. "Link": template.URL("tel:+886-2-1234-5678"),
  16. }
  17. if err := t.Execute(os.Stdout, data); err != nil {
  18. fmt.Println(err)
  19. }
  20. }

輸出:
  1. plain: &lt;em&gt;hello&lt;/em&gt;
  2. trusted: <em>hello</em>
  3. <a href="tel:&#43;886-2-1234-5678">tel</a>

tel: 不在預設允許的協定(http、https、mailto)中,若沒有轉成 template.URL 會被換成 #ZgotmplZ。

define 與 ExecuteTemplate(版型組合)


網站常見「共用版型 + 各頁內容」的結構。在版型裡用 {{block "name" .}}預設內容{{end}} 留一個可被替換的區塊,各頁用 {{define "name"}} 提供自己的內容。Clone 複製一份已解析的範本,讓不同頁面各自覆寫區塊而不互相影響。
注意:html/template 的範本第一次執行後就不能再 Parse 新內容(會回傳錯誤),所以要在執行前 Clone 出各頁的範本。
簽名:
  1. func (t *Template) ExecuteTemplate(wr io.Writer, name string, data any) error
  2. func (t *Template) Clone() (*Template, error)

範例:
  1. package main
  2. import (
  3. "fmt"
  4. "html/template"
  5. "os"
  6. )
  7. const layout = `<html><title>{{block "title" .}}My Site{{end}}</title>
  8. <body>{{block "content" .}}{{end}}</body></html>
  9. `
  10. func main() {
  11. base := template.Must(template.New("layout").Parse(layout))
  12. home := template.Must(template.Must(base.Clone()).Parse(
  13. `{{define "content"}}<h1>Welcome, {{.}}</h1>{{end}}`))
  14. about := template.Must(template.Must(base.Clone()).Parse(
  15. `{{define "title"}}About{{end}}{{define "content"}}<p>About {{.}}</p>{{end}}`))
  16. if err := home.ExecuteTemplate(os.Stdout, "layout", "<Gopher>"); err != nil {
  17. fmt.Println(err)
  18. }
  19. if err := about.ExecuteTemplate(os.Stdout, "layout", "Go"); err != nil {
  20. fmt.Println(err)
  21. }
  22. }

輸出:
  1. <html><title>My Site</title>
  2. <body><h1>Welcome, &lt;Gopher&gt;</h1></body></html>
  3. <html><title>About</title>
  4. <body><p>About Go</p></body></html>

搭配 net/http 輸出網頁


實務上 html/template 最常和 net/http 一起用:處理函式把 http.ResponseWriter 當成 io.Writer 傳給 Execute。範本在程式啟動時解析一次,每個請求只執行。
範例用 httptest 在本機起一個伺服器,不需要連外網。
範例:
  1. package main
  2. import (
  3. "fmt"
  4. "html/template"
  5. "io"
  6. "net/http"
  7. "net/http/httptest"
  8. )
  9. var page = template.Must(template.New("hello").Parse(
  10. `<p>Hello, {{.}}!</p>`))
  11. func handler(w http.ResponseWriter, r *http.Request) {
  12. name := r.URL.Query().Get("name")
  13. if name == "" {
  14. name = "guest"
  15. }
  16. w.Header().Set("Content-Type", "text/html; charset=utf-8")
  17. if err := page.Execute(w, name); err != nil {
  18. http.Error(w, "render failed", http.StatusInternalServerError)
  19. }
  20. }
  21. func main() {
  22. srv := httptest.NewServer(http.HandlerFunc(handler))
  23. defer srv.Close()
  24. for _, q := range []string{"", "?name=Gopher", "?name=%3Cb%3Ex%3C/b%3E"} {
  25. resp, err := http.Get(srv.URL + q)
  26. if err != nil {
  27. fmt.Println(err)
  28. return
  29. }
  30. body, _ := io.ReadAll(resp.Body)
  31. resp.Body.Close()
  32. fmt.Println(string(body))
  33. }
  34. }

輸出:
  1. <p>Hello, guest!</p>
  2. <p>Hello, Gopher!</p>
  3. <p>Hello, &lt;b&gt;x&lt;/b&gt;!</p>

HTMLEscapeString


不透過範本、單純把一段字串跳脫成安全的 HTML 文字。適合少量手動組字串的場合;大量 HTML 輸出仍建議用範本。
簽名:
  1. func HTMLEscapeString(s string) string

範例:
  1. package main
  2. import (
  3. "fmt"
  4. "html/template"
  5. )
  6. func main() {
  7. fmt.Println(template.HTMLEscapeString(`<a href="x">Tom & Jerry's</a>`))
  8. }

輸出:
  1. &lt;a href=&#34;x&#34;&gt;Tom &amp; Jerry&#39;s&lt;/a&gt;

重點整理


  • 輸出 HTML 一律用 html/template;語法與 text/template 相同
  • 套件依資料所在位置(文字、屬性、URL、script)自動選擇跳脫方式
  • 看到 #ZgotmplZ 代表有不安全的值被擋下
  • template.HTML、template.URL 會跳過跳脫,只能用在你能保證安全的內容
  • 範本在啟動時解析一次;需要多頁版型時先 Clone 再覆寫區塊

資料來源