动进行不同格式的转义。
例如,一个handler函数的代码如下:
func process(w http.ResponseWriter, r *http.Request) {
t, _ := template.ParseFiles("test.html")
content := `I asked: <i>"What's up?"</i>`
t.Execute(w, content)
}
上面content是Execute的第二个参数,它的内容是包含了特殊符号的字符串。
下面是test.html文件的内容:
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>Go Web Programming</title>
</head>
<body>
<div>{{ . }}</div>
<div><a href="/{{ . }}">Path</a></div>
<div><a href="/?q={{ . }}">Query</a></div>
<div><a onclick="f('{{ . }}')">Onclick</a></div>
</body>
</html>
上面test.html中有4个不同的环境,分别是html环境、url的path环境、url的query环境以及js环境。虽然对象都是{{.}}
,但解析执行后的值是不一样的。如果使用curl获取源代码,结果将如下:
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>Go Web Programming</title>
</head>
<body>
<div>I asked: <i>"What's up?"</i></div>
<div>
<a href="/I%20asked:%20%3ci%3e%22What%27s%20up?%22%3c/i%3e">
Path
</a>
</div>
<div>
<a href="/?q=I%20asked%3a%20%3ci%3e%22What%27s%20up%3f%22%3c%2fi%3e">
Query
</a>
</div>
<div>
<a onclick="f('I asked: \x3ci\x3e\x22What\x27s up?\x22\x3c\/i\x3e')">
Onclick
</a>
</div>
</body>
</html>
不转义
上下文感知的自动转义能让程序更加安全,比如防止XSS攻击(例如在表单中输入带有<script>...</script>
的内容并提交,会使得用户提交的这部分script被执行)。
如果确实不想转义,可以进行类型转换。
type CSS
type HTML
type JS
type URL
转换成指定个时候,字符都将是字面意义。
例如:
func process(w http.ResponseWriter, r *http.Request) {
t, _ := template.ParseFiles("tmpl.html")
t.Execute(w, template.HTML(r.FormValue("comment")))
}