WebSockets provide a powerful and fast connection between a client and a server, making real-time applications such as chat applications, live notifications, and streaming services run smoothly. In this article, we'll explore how to send and receive JSON messages over WebSockets in Go, making your real-time solutions efficient and effective.
Setting Up Your Go Environment
Before diving into WebSockets, ensure you have Go installed on your machine. You can download it from the official Go website. Initialize a new Go project using the following commands:
$ mkdir go-websocket-example
$ cd go-websocket-example
$ go mod init go-websocket-exampleInstalling Gorilla WebSocket Package
The Gorilla WebSocket package is a popular choice for handling WebSocket connections in Go. Install it using:
$ go get -u github.com/gorilla/websocketCreating a WebSocket Server
First, create a simple WebSocket server. The server will use the Gorilla WebSocket package to upgrade HTTP connections to WebSocket connections, handle incoming connections, and broadcast messages to connected clients.
package main
import (
"fmt"
"net/http"
"github.com/gorilla/websocket"
)
var upgrader = websocket.Upgrader{
CheckOrigin: func(r *http.Request) bool {
return true
},
}
func handleConnections(w http.ResponseWriter, r *http.Request) {
ws, err := upgrader.Upgrade(w, r, nil)
if err != nil {
fmt.Println(err)
return
}
defer ws.Close()
for {
var msg map[string]interface{}
err := ws.ReadJSON(&msg)
if err != nil {
fmt.Println("error:", err)
break
}
fmt.Printf("Received message: %v\n", msg)
}
}
func main() {
http.HandleFunc("/ws", handleConnections)
fmt.Println("Server started on :8080")
err := http.ListenAndServe(":8080", nil)
if err != nil {
panic("ListenAndServe: " + err.Error())
}
}This code snippet sets up a Go server that listens for WebSocket connections on port 8080 and outputs any received JSON message.
Creating a WebSocket Client
To interact with our Go WebSocket server, let's create a simple WebSocket client using JavaScript in an HTML file.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>WebSocket Client</title>
</head>
<body>
<script>
const socket = new WebSocket('ws://localhost:8080/ws');
socket.onopen = function() {
console.log('Connected to server');
socket.send(JSON.stringify({
message: "Hello, Server!",
date: new Date()
}));
};
socket.onmessage = function(event) {
console.log('Message from server', event.data);
};
</script>
</body>
</html>This client sends a JSON message to the WebSocket server once the connection is established.
Conclusion
In this guide, we learned how to set up a basic WebSocket server and client, and how to work with JSON messages between them using Go. This setup provides the foundation for building robust real-time applications that require continuous and immediate data exchange.