如何使用golang websockets解码多种消息类型? [英] How can you decode multiple message types with golang websockets?

查看:86
本文介绍了如何使用golang websockets解码多种消息类型?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个使用(相对)标准的 go.net/websocket < a>库。我试图从一个网页接收和解码消息,这些消息对于每种消息都有不同的结构,例如

  {类型:messagetype,msg:{/ *每个消息类型的结构不同* /}} 

有没有办法对消息进行部分解码,在继续将实际消息解码为go结构之前,只检查类型字段?



这是否需要编写自定义的 Codec ,a JSON ,使用 使用 使用json.RawMessage 来延迟解码,例如

  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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆