How to send and receive JSON data over a WebSocket connection in Go?

To send and receive JSON data over a WebSocket connection in Go, you can use the gorilla/websocket package, which provides a high-level API for working with WebSockets. Here's an example of how you can accomplish this:

  1. Import the required packages:
import ( "encoding/json" "github.com/gorilla/websocket" )
  1. Establish a WebSocket connection:
conn, _, err := websocket.DefaultDialer.Dial("ws://example.com/socket", nil) if err != nil { // handle error } defer conn.Close()
  1. Define a struct to represent your JSON data:
type Message struct { Content string `json:"content"` }
  1. Send JSON data over the WebSocket connection:
message := Message{Content: "Hello, World!"} jsonData, err := json.Marshal(message) if err != nil { // handle error } err = conn.WriteMessage(websocket.TextMessage, jsonData) if err != nil { // handle error }
  1. Receive JSON data from the WebSocket connection:
_, jsonData, err := conn.ReadMessage() if err != nil { // handle error } var receivedMessage Message err = json.Unmarshal(jsonData, &receivedMessage) if err != nil { // handle error } // Access received JSON data using receivedMessage.Content

That's it! You can use these steps to send and receive JSON data over a WebSocket connection in Go. Remember to handle errors appropriately in your application.