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

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 HFSS 中的 H 场图与 MATLAB 中绘制的 B1 场 部分对应不上
  • ¥15 如何在scanpy上做差异基因和通路富集?
  • ¥20 关于#硬件工程#的问题,请各位专家解答!
  • ¥15 关于#matlab#的问题:期望的系统闭环传递函数为G(s)=wn^2/s^2+2¢wn+wn^2阻尼系数¢=0.707,使系统具有较小的超调量
  • ¥15 FLUENT如何实现在堆积颗粒的上表面加载高斯热源
  • ¥30 截图中的mathematics程序转换成matlab
  • ¥15 动力学代码报错,维度不匹配
  • ¥15 Power query添加列问题
  • ¥50 Kubernetes&Fission&Eleasticsearch
  • ¥15 報錯:Person is not mapped,如何解決?