实现说明
全部逻辑都在函数 strictDecode、main中。
在这里做循环的是 for _, c := range []struct。err 在 2 个调用点被检查,之后才会使用其他结果。
使用要点
- 错误是普通返回值;跳过
err检查就意味着静默使用零值。 - 跑完文件,输出里会留下标记——
unmarshal with tail:。 main按顺序串起strictDecode;运行文件就会把这个流程跑一遍。
常见问题
调用失败时会发生什么?
以返回值上报:每个可能失败的调用都交回 error,这里有 2 处检查。
运行「Decoder 拒绝带尾巴的 JSON」会打印什么?
运行文件本身,unmarshal with tail: 这些前缀各对应一段演示逻辑。
主要签名是 func strictDecode(data []byte) (Event, error)
核心语句
return Event{}, errors.New("trailing data after JSON value")
if err != nil {
fmt.Printf("%-10s rejected: %v\n", c.name, err)
continue
}
代码示例
package main
import (
"bytes"
"encoding/json"
"errors"
"fmt"
"io"
)
type Event struct {
Type string `json:"type"`
At int64 `json:"at"`
}
func strictDecode(data []byte) (Event, error) {
dec := json.NewDecoder(bytes.NewReader(data))
var e Event
if err := dec.Decode(&e); err != nil {
return Event{}, err
}
// 尾巴检测:第二次 Decode 必须恰好命中 io.EOF
var extra any
if err := dec.Decode(&extra); err != io.EOF {
if err == nil {
return Event{}, errors.New("trailing data after JSON value")
}
return Event{}, err
}
return e, nil
}
func main() {
good := []byte(`{"type":"login","at":1731628800}`)
tail := []byte(`{"type":"login","at":1731628800} {"type":"evil"}`)
trunc := []byte(`{"type":"login"`)
for _, c := range []struct {
name string
input []byte
}{
{"good", good},
{"with tail", tail},
{"truncated", trunc},
} {
e, err := strictDecode(c.input)
if err != nil {
fmt.Printf("%-10s rejected: %v\n", c.name, err)
continue
}
fmt.Printf("%-10s ok: %+v\n", c.name, e)
}
// 对照:Unmarshal 对尾巴视而不见,照样成功
var ignored Event
fmt.Println("unmarshal with tail:", json.Unmarshal(tail, &ignored) == nil)
}