1.4 服务器端渲染

1.4.1【必须】模板渲染过滤验证

  • 使用text/template或者html/template渲染模板时禁止将外部输入参数引入模板,或仅允许引入白名单内字符。
  1. // bad
  2. func handler(w http.ResponseWriter, r *http.Request) {
  3. r.ParseForm()
  4. x := r.Form.Get("name")
  5. var tmpl = `<!DOCTYPE html><html><body>
  6. <form action="/" method="post">
  7. First name:<br>
  8. <input type="text" name="name" value="">
  9. <input type="submit" value="Submit">
  10. </form><p>` + x + ` </p></body></html>`
  11. t := template.New("main")
  12. t, _ = t.Parse(tmpl)
  13. t.Execute(w, "Hello")
  14. }
  15. // good
  16. import (
  17. "fmt"
  18. "github.com/go-playground/validator/v10"
  19. )
  20. var validate *validator.Validate
  21. validate = validator.New()
  22. func validateVariable(val) {
  23. errs := validate.Var(val, "gte=1,lte=100")//限制必须是1-100的正整数
  24. if errs != nil {
  25. fmt.Println(errs)
  26. return False
  27. }
  28. return True
  29. }
  30. func handler(w http.ResponseWriter, r *http.Request) {
  31. r.ParseForm()
  32. x := r.Form.Get("name")
  33. if validateVariable(x):
  34. var tmpl = `<!DOCTYPE html><html><body>
  35. <form action="/" method="post">
  36. First name:<br>
  37. <input type="text" name="name" value="">
  38. <input type="submit" value="Submit">
  39. </form><p>` + x + ` </p></body></html>`
  40. t := template.New("main")
  41. t, _ = t.Parse(tmpl)
  42. t.Execute(w, "Hello")
  43. else:
  44. ...
  45. }