1.4 服务器端渲染
1.4.1【必须】模板渲染过滤验证
- 使用
text/template
或者html/template
渲染模板时禁止将外部输入参数引入模板,或仅允许引入白名单内字符。
// bad
func handler(w http.ResponseWriter, r *http.Request) {
r.ParseForm()
x := r.Form.Get("name")
var tmpl = `<!DOCTYPE html><html><body>
<form action="/" method="post">
First name:<br>
<input type="text" name="name" value="">
<input type="submit" value="Submit">
</form><p>` + x + ` </p></body></html>`
t := template.New("main")
t, _ = t.Parse(tmpl)
t.Execute(w, "Hello")
}
// good
import (
"fmt"
"github.com/go-playground/validator/v10"
)
var validate *validator.Validate
validate = validator.New()
func validateVariable(val) {
errs := validate.Var(val, "gte=1,lte=100")//限制必须是1-100的正整数
if errs != nil {
fmt.Println(errs)
return False
}
return True
}
func handler(w http.ResponseWriter, r *http.Request) {
r.ParseForm()
x := r.Form.Get("name")
if validateVariable(x):
var tmpl = `<!DOCTYPE html><html><body>
<form action="/" method="post">
First name:<br>
<input type="text" name="name" value="">
<input type="submit" value="Submit">
</form><p>` + x + ` </p></body></html>`
t := template.New("main")
t, _ = t.Parse(tmpl)
t.Execute(w, "Hello")
else:
...
}