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:
import (
"encoding/json"
"github.com/gorilla/websocket"
)
conn, _, err := websocket.DefaultDialer.Dial("ws://example.com/socket", nil)
if err != nil {
// handle error
}
defer conn.Close()
type Message struct {
Content string `json:"content"`
}
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
}
_, 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.