简体   繁体   中英

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. 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 ... \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:

fmt.Printf("Received command: %v (Error: %s)\n", 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)\n", 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 ... \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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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