简体   繁体   English

golang:json.Unmarshal()返回“无效的内存地址或nil指针取消引用”

[英]golang: json.Unmarshal() returns “invalid memory address or nil pointer dereference”

I get a json message from a websocket an the json string is received ok. 我从websocket收到json消息,并且json字符串接收正常。 Then I call json.Unmarshal an get a runtime panic. 然后我打电话给json.Unmarshal一个运行时的恐慌。 I looked through the other examples, but this seems to be something else. 我浏览了其他示例,但这似乎是另外一回事。 Here is the code: 这是代码:

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())
        }
    }
}

And this is the output: 这是输出:

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)

Any hint what that could be? 有什么暗示吗?

This line will panic if there's no error decoding the JSON: 如果解码JSON时没有错误,则此行会出现恐慌:

fmt.Printf("Received command: %v (Error: %s)\n", command, err.Error())

If err == nil, then err.Error() panics with nil pointer derference. 如果err == nil,则err.Error()会因nil指针递减而发生混乱。 Change the line to: 将行更改为:

fmt.Printf("Received command: %v (Error: %v)\n", command, err)

If you are reading a socket, then there's no guarantee that s.Read() will read a complete JSON value. 如果您正在读取套接字,则无法保证s.Read()将读取完整的JSON值。 A better way to write this function is: 编写此函数的更好方法是:

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
      }
  }
}

If you are working with websockets, then you should use the gorilla/webscoket package and ReadJSON to decode JSON values. 如果使用的是websocket,则应使用gorilla / webscoket包和ReadJSON解码JSON值。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM