How can you decode multiple types of messages using golang websockets?

I have a go program using the (relatively) standard go.net/websocket library. I am 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 a way to do a β€œpartial” decoding of a message only by checking the type field before proceeding to decrypt the actual message in go struct?

Does this require writing a custom Codec , a'la JSON , which delegates the JSON codec to the message itself?

+6
source share
1 answer

Use json.RawMessage to delay decoding, e.g.

 struct { type string msg json.RawMessage } 

json.RawMessage is an alias for []byte , which can then be decoded as you wish.

+11
source

All Articles