实现说明
进入 HTML 前先转义字符串以函数 main为骨架。
使用要点
- 演示输出是带标签的(
orig:),每个操作都会留下自己的一行标注。
常见问题
运行「进入 HTML 前先转义字符串」会打印什么?
不用做任何设置,直接把文件跑完——输出里的 orig: 标签标明各步骤。
核心语句
single := html.EscapeString(comment)
代码示例
package main
import (
"fmt"
"html"
)
func main() {
// User-controlled text concatenated straight into an HTML page is executed as markup
comment := `<script>alert("xss")</script> & "quotes" 'apostrophes'`
// EscapeString turns < > & ' " into entities: the browser renders them as plain text
fmt.Println(html.EscapeString(comment))
// UnescapeString reverses entities back into characters
escaped := "Tom & Jerry <3"
fmt.Println(html.UnescapeString(escaped))
// Escaping grows the string: lengths of the original, once-escaped, and double-escaped forms
single := html.EscapeString(comment)
double := html.EscapeString(single)
fmt.Println("orig:", len(comment), "escaped:", len(single), "double:", len(double))
}