英文:
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.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论