JSON Encoder Controls HTML Escaping
SetEscapeHTML on a json.Encoder decides whether <, >, and & ship as unicode escapes, the default that keeps JSON safe to embed in HTML pages.
Code
package main
import (
"bytes"
"encoding/json"
"fmt"
)
type Profile struct {
Name string `json:"name"`
Bio string `json:"bio"`
}
func encode(profile Profile, escapeHTML bool) string {
var buf bytes.Buffer
encoder := json.NewEncoder(&buf)
// 默认 true:<、>、& 编码成 \u003c、\u003e、\u0026,JSON 可安全嵌入 HTML
encoder.SetEscapeHTML(escapeHTML)
if err := encoder.Encode(profile); err != nil {
return err.Error()
}
// Encode 末尾自带换行,返回前去掉
return string(bytes.TrimRight(buf.Bytes(), "\n"))
}
func main() {
profile := Profile{Name: "Ada", Bio: "R&D & <core> team"}
fmt.Println("default :", encode(profile, true))
fmt.Println("unescaped:", encode(profile, false))
}Line-by-line reading
What another module actually calls is the functions encode and main — everything else is wiring.
The Go idiom runs throughout — 1 if err != nil check, each handling the failure on the spot.
What to watch for
- No panic path here — failures come back as
errorvalues that each caller must handle.
Putting it to use
The primary signature, spelled out, is func encode(profile Profile, escapeHTML bool) string
Look for the default :, unescaped: prefixes as the file executes; they connect every printed line to the step behind it.
The sequence encode lives in main; running the file triggers it.
Core lines
func main() {
profile := Profile{Name: "Ada", Bio: "R&D & <core> team"}
fmt.Println("default :", encode(profile, true))
fmt.Println("unescaped:", encode(profile, false))
}
return string(bytes.TrimRight(buf.Bytes(), "\n"))
return err.Error()
Interactive Tools for This Topic
HTML Entity Encoder / DecoderEncode the five HTML-significant characters and decode named or numeric entities, with optional numeric encoding for non-ASCII text.Multi-Mode Escape & Unescape CodecEscape and unescape strings safely across JSON, JavaScript, SQL single-quoted literals, POSIX shell single quotes, and RFC 4180 CSV cells in your browser.Regex Escape GeneratorEscape plain text so it can be embedded safely in a JavaScript RegExp, covering all metacharacters like dots, brackets, braces, and backslashes.Argon2id Hash InfoEstimate Argon2id password-hash latency and memory usage, and check your parameters against OWASP 2024 minimum and recommended settings.
FAQ
- Is there exception handling?
- No exceptions — `error` returns checked at 1 site, and callers branch on `err` first.
- What does JSON Encoder Controls HTML Escaping print when run?
- Execute the whole file; each printed line is prefixed with a label like `default :`, `unescaped:`.
Report a problem with this exampleOpens a pre-filled issue on GitHub.