From the course: Effective Serialization In Go: JSON, Protocol Buffers and More

Unlock this course with a free trial

Join today to access over 25,500 courses taught by industry experts.

Handling dynamic types

Handling dynamic types

- [Instructor] In some cases your API might get different type of messages. I'm going to show you two different ways how to handle that situation. The first one, if you're going to have a message that contains the type and then inside it embedded is the actual message. For example, let's say we have door events from an elevator. So an event has a type, it has a payload. And the payload can be either a door event, meaning some kind of an action, opening or closing the door and the floor, or a button event saying the button was pressed. And we are using JSON raw message. Here is JSON raw message in the API. And when you say that you're using a raw message as the type, the encoding JSON is not going to parse any of the underlying type. Okay, so here's our function. We have a handle event. We create first the top level event, and we do un-marshaling. And then we do switch on the type. If it's a door type, we are going to create a door event now and do un-marshal on the payload, on the…

Contents