doujiaohuo1096
2015-01-18 16:36
浏览 147

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

I get a json message from a websocket an the json string is received ok. Then I call json.Unmarshal an get a runtime panic. 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 ... 
")
        if n, err := s.Read(message); err == nil {
            command := map[string]interface{}{}
            fmt.Printf("Received message: %v (%d Bytes)
", string(message[:n]), n)
            err := json.Unmarshal(message[:n],&command)
            fmt.Printf("Received command: %v (Error: %s)
", 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?

  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 邀请回答

1条回答 默认 最新

  • dph23577 2015-01-18 16:47
    已采纳

    This line will panic if there's no error decoding the JSON:

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

    If err == nil, then err.Error() panics with nil pointer derference. Change the line to:

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

    If you are reading a socket, then there's no guarantee that s.Read() will read a complete JSON value. A better way to write this function is:

    func translateMessages(s socket) {
      d := json.NewDecoder(s)
      for {
          fmt.Printf("Waiting for a message ... 
    ")
          var command map[string]interface{}
          err := d.Decode(&command)
          fmt.Printf("Received command: %v (Error: %v)
    ", 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.

    点赞 打赏 评论

相关推荐 更多相似问题