有些奇怪的东西我不明白。 在行中是:
err = dec.Decode(&struct{}{})
我有这个功能:
func (app *Config) readJSON(w http.ResponseWriter,r http.Request,data any) error {
maxBytes := 1048576
r.Body = http.MaxBytesReader(w,r.Body,int64(maxBytes))
dec := json.NewDecoder(r.Body)
err := dec.Decode(data)
if err != nil {
return err
}
err = dec.Decode(&struct{}{})
if err != io.EOF {
return errors.New("Body must have only a single JSON body")
}
return nil
}
只有一个 json 主体的行背后的逻辑是什么: 在: 为什么我需要将 ref 传递给 Decode 函数中的双花括号?
dec.Decode(&struct{}{})
为什么只使用“=”而不使用“:=”?
这是doc
(*Decoder).Decode
func (dec *Decoder) Decode(v any) error
Decode 从其输入中读取下一个 JSON 编码值并将其存储在 v 指向的值中。
也就是说解码如下内容有效(读取第一个json对象):
{
"a":1
}
{
"b":2
}
readJSON
想要阻止这种输入,所以它调用err = dec.Decode(&struct{}{})
来检查解码器是否已经到达输入的末尾。
struct{}
定义一个类型,struct{}{}
创建该类型的一个新实例,并且 &struct{}{}
引用该新实例。相当于
type empty struct{}
e := empty{}
err = dec.Decode(&e)
(*Decoder).More
比较好
为什么只使用“=”而不使用“:=”?
:=
用于简短的变量声明。之前已经声明了变量err
。这里我们只想给它赋一个新值,不想再声明一次,所以用了=