[英]golang: json.Unmarshal() returns “invalid memory address or nil pointer dereference”
我从websocket收到json消息,并且json字符串接收正常。 然后我打电话给json.Unmarshal一个运行时的恐慌。 我浏览了其他示例,但这似乎是另外一回事。 这是代码:
func translateMessages(s socket) {
message := make([]byte,4096)
for {
fmt.Printf("Waiting for a message ... \n")
if n, err := s.Read(message); err == nil {
command := map[string]interface{}{}
fmt.Printf("Received message: %v (%d Bytes)\n", string(message[:n]), n)
err := json.Unmarshal(message[:n],&command)
fmt.Printf("Received command: %v (Error: %s)\n", command, err.Error())
}
}
}
这是输出:
Waiting for a message ...
Received message: {"gruss":"Hello World!"} (24 Bytes)
panic: runtime error: invalid memory address or nil pointer dereference
[signal 0xb code=0x1 addr=0x20 pc=0x401938]
goroutine 25 [running]:
runtime.panic(0x6f4860, 0x8ec333)
有什么暗示吗?
如果解码JSON时没有错误,则此行会出现恐慌:
fmt.Printf("Received command: %v (Error: %s)\n", command, err.Error())
如果err == nil,则err.Error()会因nil指针递减而发生混乱。 将行更改为:
fmt.Printf("Received command: %v (Error: %v)\n", command, err)
如果您正在读取套接字,则无法保证s.Read()将读取完整的JSON值。 编写此函数的更好方法是:
func translateMessages(s socket) {
d := json.NewDecoder(s)
for {
fmt.Printf("Waiting for a message ... \n")
var command map[string]interface{}
err := d.Decode(&command)
fmt.Printf("Received command: %v (Error: %v)\n", command, err)
if err != nil {
return
}
}
}
如果使用的是websocket,则应使用gorilla / webscoket包和ReadJSON解码JSON值。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.