type Message struct { Text string Time time.Time } conn, err := websocket.Upgrade(w, r, nil, 1024, 1024) if err != nil { // Handle error } var msg Message err = conn.ReadJSON(&msg) if err != nil { // Handle error } fmt.Printf("Received message: %v", msg)
type Command struct { Operation string Args []string } conn, err := gorilla.Dial("ws://localhost:8080/ws", nil) if err != nil { // Handle error } cmd := Command{ Operation: "ping", Args: []string{"arg1", "arg2"}, } err = conn.WriteJSON(&cmd) if err != nil { // Handle error } var resp Command err = conn.ReadJSON(&resp) if err != nil { // Handle error } fmt.Printf("Received response: %v", resp)In this example, we first establish a WebSocket connection using the `gorilla.Dial` function. We then construct a JSON message `cmd` and send it to the server using the `conn.WriteJSON` method. Finally, we wait for a response message from the server using the `conn.ReadJSON` method and unmarshal the message into the `resp` variable. Overall, Conn ReadJSON is a useful method provided by the gorilla/websocket package for reading JSON-encoded messages from WebSocket connections.