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.

GoSecurity Boundaries

Code

snippet
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 error values 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

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:`.