16
16
我们看4.1小节的例子
17
17
``` Go
18
18
19
- fmt.Println (" username:" , template.HTMLEscapeString (r.Form .Get (" username" ))) // 输出到服务器端
20
- fmt.Println (" password:" , template.HTMLEscapeString (r.Form .Get (" password" )))
21
- template.HTMLEscape (w, []byte (r.Form .Get (" username" ))) // 输出到客户端
19
+ fmt.Println (" username:" , template.HTMLEscapeString (r.Form .Get (" username" ))) // 输出到服务器端
20
+ fmt.Println (" password:" , template.HTMLEscapeString (r.Form .Get (" password" )))
21
+ template.HTMLEscape (w, []byte (r.Form .Get (" username" ))) // 输出到客户端
22
22
```
23
23
如果我们输入的username是` <script>alert()</script> ` ,那么我们可以在浏览器上面看到输出如下所示:
24
24
29
29
Go的html/template包默认帮你过滤了html标签,但是有时候你只想要输出这个` <script>alert()</script> ` 看起来正常的信息,该怎么处理?请使用text/template。请看下面的例子:
30
30
``` Go
31
31
32
- import " text/template"
33
- ...
34
- t , err := template.New (" foo" ).Parse (` {{define "T"}}Hello, {{.}}!{{end}}` )
35
- err = t.ExecuteTemplate (out, " T" , " <script>alert('you have been pwned')</script>" )
32
+ import " text/template"
33
+ ...
34
+ t , err := template.New (" foo" ).Parse (` {{define "T"}}Hello, {{.}}!{{end}}` )
35
+ err = t.ExecuteTemplate (out, " T" , " <script>alert('you have been pwned')</script>" )
36
36
```
37
37
输出
38
38
@@ -41,10 +41,10 @@ Go的html/template包默认帮你过滤了html标签,但是有时候你只想
41
41
或者使用template.HTML类型
42
42
``` Go
43
43
44
- import " html/template"
45
- ...
46
- t , err := template.New (" foo" ).Parse (` {{define "T"}}Hello, {{.}}!{{end}}` )
47
- err = t.ExecuteTemplate (out, " T" , template.HTML (" <script>alert('you have been pwned')</script>" ))
44
+ import " html/template"
45
+ ...
46
+ t , err := template.New (" foo" ).Parse (` {{define "T"}}Hello, {{.}}!{{end}}` )
47
+ err = t.ExecuteTemplate (out, " T" , template.HTML (" <script>alert('you have been pwned')</script>" ))
48
48
```
49
49
输出
50
50
@@ -55,10 +55,10 @@ Go的html/template包默认帮你过滤了html标签,但是有时候你只想
55
55
转义的例子:
56
56
``` Go
57
57
58
- import " html/template"
59
- ...
60
- t , err := template.New (" foo" ).Parse (` {{define "T"}}Hello, {{.}}!{{end}}` )
61
- err = t.ExecuteTemplate (out, " T" , " <script>alert('you have been pwned')</script>" )
58
+ import " html/template"
59
+ ...
60
+ t , err := template.New (" foo" ).Parse (` {{define "T"}}Hello, {{.}}!{{end}}` )
61
+ err = t.ExecuteTemplate (out, " T" , " <script>alert('you have been pwned')</script>" )
62
62
```
63
63
转义之后的输出:
64
64
0 commit comments