你可以使用golang websockets如何解码多种消息类型?

huangapple go评论79阅读模式
英文:

How can you decode multiple message types with golang websockets?

问题

我有一个使用(相对)标准的go.net/websocket‎库的Go程序。我试图接收和解码来自网页的消息,每种消息类型的结构都不同,例如:

{type: "messagetype", msg: { /* 每种消息类型的结构都不同 */ } }

有没有办法在解码实际消息之前,只对type字段进行“部分”解码?这是否需要编写一个自定义的Codec,类似于JSON,它将委托给消息本身的JSON编解码器?

英文:

I have a go program using the (relatively) standard go.net/websocket‎ library. I'm trying to receive and decode messages from a web page that have a different structure for each type of message, i.e.

{type: "messagetype", msg: { /* structure different for each message type */ } }

Is there any way to do a "partial" decode of the message, only checking the type field before proceeding to decode the actual message into a go struct?

Would this necessitate writing a custom Codec, a'la JSON, that delegates to the JSON codec for the message itself?

答案1

得分: 14

使用json.RawMessage来延迟解码,例如:

struct {
    type string
    msg  json.RawMessage
}

json.RawMessage[]byte的别名,你可以根据需要进一步解码。

英文:

Use json.RawMessage to delay the decoding, eg

struct {
    type string
    msg  json.RawMessage
}

json.RawMessage is an alias for []byte which you can then further decode as you wish.

huangapple
  • 本文由 发表于 2014年4月14日 14:41:48
  • 转载请务必保留本文链接:https://go.coder-hub.com/23053563.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定