
Go’s html.EscapeString() function reliably converts special HTML characters (like , ", ', and &) into their corresponding safe HTML entities, preventing XSS and ensuring raw text is displayed literally in browsers.
go’s html.escapestring() function reliably converts special html characters (like , ", ', and &) into their corresponding safe html entities, preventing xss and ensuring raw text is displayed literally in browsers.
When rendering user-provided or dynamic content in HTML contexts—such as embedding data inside
Here’s how to use it:
package main
import (
"fmt"
"html"
)
func main() {
raw := `<script>alert(123);</script>`
escaped := html.EscapeString(raw)
fmt.Println(escaped)
// Output: <script>alert(123);</script>
}
✅ Key behavior:
- > → >
- " → "
- ' → '
- & → &
⚠️ Important notes:
- html.EscapeString() is not for escaping HTML inside <script> or <style> tags — those require context-aware escaping (e.g., using json.Marshal for inline scripts). </script>
- It does not sanitize or remove HTML tags — it only escapes characters so they’re rendered as visible text, not parsed as markup.
- For templating, prefer html/template (which auto-escapes by default) over text/template; it provides contextual auto-escaping for HTML, JS, CSS, and URLs.
In summary: use html.EscapeString() when you need to safely interpolate plain text into HTML content — it’s simple, secure, and part of Go’s trusted standard library.
前端入门到VUE实战笔记:立即使用
在学习笔记中,你将探索 前端 的入门与实战技巧!











