Home >Backend Development >Golang >How to Handle Incoming WebSocket JSON Messages with Different Structures in Golang?
Serialization and deserialization of JSON data is crucial in WebSocket communication. In Go, the gorilla websocket library provides a convenient way to send and receive JSON messages. However, when dealing with multiple structs, determining their type can become a challenge.
To handle this scenario, consider using a generic message structure like below:
type Messages struct { Control string `json:"control"` X json.RawMessage }
In this structure, Control specifies the type of the incoming message, while X is an untyped field that can hold the actual data.
To handle the incoming message, follow these steps:
Read the message into a Messages struct:
var m Messages err := c.ReadJSON(&m) if err != nil { // handle error }
Based on the value of Control, determine the data type:
switch m.Control { case "Foo": var foo Foo if err := json.Unmarshal([]byte(m.X), &foo); err != nil { // handle error } // do something with foo } ... // Handle other cases similarly
By utilizing json.RawMessage, you gain flexibility in handling multiple data types. This approach allows you to dynamically deserialize incoming messages based on their specified type.
The above is the detailed content of How to Handle Incoming WebSocket JSON Messages with Different Structures in Golang?. For more information, please follow other related articles on the PHP Chinese website!