如何使用golang websockets解码多种消息类型? [英] How can you decode multiple message types with golang websockets?
问题描述
我有一个使用(相对)标准的 go.net/websocket < a>库。我试图从一个网页接收和解码消息,这些消息对于每种消息都有不同的结构,例如
{类型:messagetype,msg:{/ *每个消息类型的结构不同* /}}
有没有办法对消息进行部分解码,在继续将实际消息解码为go结构之前,只检查类型
字段?
这是否需要编写自定义的 Codec
,a
struct {
type string
msg json.RawMessage
}
json.RawMessage
是 [] byte
的别名,您可以随意进一步解码。
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?
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.
这篇关于如何使用golang websockets解码多种消息类型?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!