Generic JSON Serialization/Deserialization for Websockets in Go
When working with websockets, the need often arises to serialize and deserialize JSON data for communication between client and server. One common challenge is handling incoming messages of different types, such as structs with varying fields.
In this scenario, using gorilla websocket and JSON for serialization and deserialization, it can be cumbersome to explicitly specify the type for each message. The conn.ReadJSON() function requires the specific type to be provided, which is not always practical when dealing with multiple message types.
A Generic Solution Using JSON Control
A generic solution involves defining a struct that contains a control field indicating the message type. This control field allows the program to determine the specific data structure to use for deserialization.
type Messages struct { Control string `json:"control"` X json.RawMessage }
This Messages struct includes a Control field and an X field, which can hold any type of JSON data as a raw message.
Deserializing and Handling Messages
When receiving a message using conn.ReadJSON(), the data can be stored in the Messages struct. The Control field can then be used to determine the actual type of data stored in the X field.
var m Messages err := c.ReadJSON(&m) if err != nil { // handle error } switch m.Control { case "Foo": var foo Foo if err := json.Unmarshal([]byte(m.X), &foo); err != nil { // handle error } // do something with foo case "Bar": // follow the same pattern for the Bar struct }
In this example, if the Control field is "Foo", the X field is deserialized into a Foo struct using json.Unmarshal(). This process can be repeated for other message types.
Benefits of this approach:
Atas ialah kandungan terperinci Bagaimana untuk Mengendalikan Pensirilan/Deserialisasi JSON untuk Pelbagai Jenis Mesej dalam Soket Web Go?. Untuk maklumat lanjut, sila ikut artikel berkaitan lain di laman web China PHP!