8

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?

Thomas
  • 11,757
  • 4
  • 41
  • 57

1 Answers1

14

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.

Nick Craig-Wood
  • 52,955
  • 12
  • 126
  • 132
  • 1
    Thank you! I almost gave up, but I really hated the idea that I need to use reflection or try/catch different unmarshalings. This is so much better. – Rob Mar 17 '20 at 13:31