doujiaohuo1096 2015-01-18 16:36
浏览 279
已采纳

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.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 乌班图ip地址配置及远程SSH
  • ¥15 怎么让点阵屏显示静态爱心,用keiluVision5写出让点阵屏显示静态爱心的代码,越快越好
  • ¥15 PSPICE制作一个加法器
  • ¥15 javaweb项目无法正常跳转
  • ¥15 VMBox虚拟机无法访问
  • ¥15 skd显示找不到头文件
  • ¥15 机器视觉中图片中长度与真实长度的关系
  • ¥15 fastreport table 怎么只让每页的最下面和最顶部有横线
  • ¥15 java 的protected权限 ,问题在注释里
  • ¥15 这个是哪里有问题啊?