How to Auto-Escape HTML in Go Templates

Web
Go templates automatically escape HTML to prevent XSS attacks, rendering special characters as safe text by default.

Go templates automatically escape HTML by default when using the {{.Variable}} syntax, converting special characters like < and > into safe entities. This prevents Cross-Site Scripting (XSS) attacks without requiring manual intervention.

tmpl := template.Must(template.New("page").Parse(`
<!DOCTYPE html>
<html>
<body>
<h1>{{.Title}}</h1>
<p>{{.Content}}</p>
</body>
</html>`))

data := map[string]string{
    "Title":   "Hello",
    "Content": "<script>alert('XSS')</script>",
}

tmpl.Execute(os.Stdout, data)

If you explicitly need to render raw HTML, use the {{.Variable | html}} action, but only if the content is trusted.