
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 <div> text, JSON-in-HTML attributes, or server-side templates—it’s critical to escape unsafe characters. Go’s standard library provides the robust and well-audited html.EscapeString function for this exact purpose.
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:
使用 Puppeteer + Chrome 将 HTML 渲染为中文 PDF,自动处理图表等待、Tab 展开、动画、测高、白边消除、防分页,适用于看板、报表、网页和交互图表转 PDF。
- < →
- > → >
- " → "
- ' → '
- & → &
⚠️ 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).
- 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.


















