簡體   English   中英

golang:json.Unmarshal()返回“無效的內存地址或nil指針取消引用”

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

我從websocket收到json消息,並且json字符串接收正常。 然后我打電話給json.Unmarshal一個運行時的恐慌。 我瀏覽了其他示例,但這似乎是另外一回事。 這是代碼:

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

這是輸出:

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)

有什么暗示嗎?

如果解碼JSON時沒有錯誤,則此行會出現恐慌:

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

如果err == nil,則err.Error()會因nil指針遞減而發生混亂。 將行更改為:

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

如果您正在讀取套接字,則無法保證s.Read()將讀取完整的JSON值。 編寫此函數的更好方法是:

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

如果使用的是websocket,則應使用gorilla / webscoket包和ReadJSON解碼JSON值。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM