
Use Go’s html.UnescapeString() function to convert HTML-encoded strings (like
use go’s html.unescapestring() function to convert html-encoded strings (like , <code>") back into their original characters (like , <code>"). it’s safe, standard, and handles all common entities—including nested or malformed ones—without manual regex or string replacement.
When working with HTML content that arrives as an escaped string—such as from user input, API responses, or templating systems—you’ll often encounter entities like , <code>>, ", ', and &. These are not literal angle brackets or quotes but HTML escape sequences meant to prevent injection or parsing errors.
In Go, the cleanest and most robust way to reverse this encoding is using the html.UnescapeString function from the golang.org/x/net/html package (note: it's not in the standard html package — a common point of confusion).
✅ Correct import and usage:
文章转信息图。将文章/笔记转化为手机可读的 HTML 信息图,自动匹配视觉风格。触发场景:文章转图、笔记转图、信息图、转小红书图、做张图、可视化这篇文章、文生图。
package main
import (
"fmt"
"golang.org/x/net/html"
)
func main() {
test1 := `<iframe src="https://www.disnei.com/embed/44bc40f3bc04f65b7a35" frameborder="0" width="100%" height="340" scrolling="no" allowfullscreen></iframe>`
unescaped := html.UnescapeString(test1)
fmt.Println(unescaped)
// Output:
// <iframe src="https://www.disnei.com/embed/44bc40f3bc04f65b7a35" frameborder="0" width="100%" height="340" scrolling="no" allowfullscreen></iframe>
}
⚠️ Important notes:
- Don’t use
strings.ReplaceAll()or regex-based “quick fixes” — they’re error-prone and fail on edge cases (e.g.,<→→ <code> requires two passes). - The
html.UnescapeStringfunction correctly handles double-escaping, numeric entities (), named entities (<code>), and even partial/broken sequences safely. - If you're using Go 1.21+, ensure your
go.modincludes the required dependency:go get golang.org/x/net/html
- This function only decodes entities — it does not sanitize or validate HTML. Never insert untrusted, unescaped HTML directly into templates or
innerHTML; always pair decoding with proper sanitization (e.g., usingbluemondayorgolang.org/x/net/htmlparsers) if rendering in browsers.
In summary: for reliable, one-step HTML entity decoding in Go, reach for golang.org/x/net/html.UnescapeString. It’s the idiomatic, battle-tested solution — no workarounds, no backslashes, no surprises.
前端入门到VUE实战笔记:立即使用
在学习笔记中,你将探索 前端 的入门与实战技巧!










