亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

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

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

Go
滄海一幻覺 2021-09-10 21:40:23
我從 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)任何提示可能是什么?
查看完整描述

1 回答

?
www說

TA貢獻1775條經驗 獲得超8個贊

如果解碼 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

      }

  }

}

如果您正在使用 websockets,那么您應該使用 gorilla/webscoket 包和ReadJSON來解碼 JSON 值。


查看完整回答
反對 回復 2021-09-10
  • 1 回答
  • 0 關注
  • 273 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號