实现说明
真正干活的是函数 encode、main,其余都是接线。
Go 惯用法贯穿始终——1 处 if err != nil,每一处就地处理失败。
使用要点
- 函数以返回
error报告失败——调用方先分支判断,再碰其他结果。 - 直接运行文件,输出会带上标签,比如
default :、unescaped:——输出的每一行都能指回产生它的那次调用。 - 执行文件,
main会按顺序走完encode。
常见问题
有异常处理吗?
没有异常——error 返回值在 1 处被检查,调用方先看 err。
运行「JSON 编码器的 HTML 转义开关」会打印什么?
整个文件跑完,输出行以 default :、unescaped: 这类前缀开头。
签名一览:func encode(profile Profile, escapeHTML bool) string
核心语句
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()
代码示例
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))
}