概述
在上一篇文章中,我们介绍了 Go 模板库text/template
。text/template
库用于生成文本输出。在 Web 开发中,涉及到很多安全方面的问题。有些数据是用户输入的,不能直接替换到模板中,否则可能导致注入攻击。Go 提供了html/template
库处理这些问题。html/template
提供了与text/template
一样的接口。我们通常使用html/template
生成 HTML 输出。
由于上一篇文章已经详细介绍了 Go 模板的基本概念,本文主要从使用的层面来介绍html/template
库。中间会有安全方面的内容。那就开始吧!
初体验
html/template
库的使用与text/template
基本一样:
package main
import (
"fmt"
"html/template"
"log"
"net/http"
)
func indexHandler(w http.ResponseWriter, r *http.Request) {
t, err := template.ParseFiles("hello.html")
if err != nil {
w.WriteHeader(500)
fmt.Fprint(w, err)
return
}
t.Execute(w, "Hello World")
}
func main() {
mux := http.NewServeMux()
mux.HandleFunc("/", indexHandler)
server := &http.Server {
Addr: ":8080",
Handler: mux,
}
if err := server.ListenAndServe(); err != nil {
log.Fatal(err)
}
}
模板文件hello.html
:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Go Web 编程之 模板(二)</title>
</head>
<body>
{
{ . }}
</body>
</html>
模板中的{
{ . }}
会被替换为传入的数据"Hello World",程序将模板执行后生成的文本通过ResponseWriter
传回客户端。
编译,运行程序(我的环境 Win10 Git Bash):
$ go build -o main.exe main.go
$ ./main.exe
打开浏览器,输入localhost:8080
,即可看到"Hello World"页面。
我们在介绍text/template
库的时候,提到了空白问题