避免XSS的方法之一主要是将用户所提供的内容进行过滤,Go语言提供了HTML的过滤函数:
text/template
包下面的HTMLEscapeString
、JSEscapeString
等函数。或者html
包下的html.EscapeString()
、html.UnescapeString()
。
1 2 3 4 5 6 7 8 9 |
import ( "text/template" ) func Xss(text string) string { text = template.HTMLEscaper(text) text = template.JSEscaper(text) return text } |
1 2 3 4 5 6 7 8 9 10 11 |
import ( "html" ) func test(text string) string { // 转义 text = html.EscapeString(text) // 恢复 text = html.UnescapeString(text) return text } |