Real-time user interfaces (UIs) are increasingly prevalent, providing dynamic updates without needing a page refresh. WebSockets facilitate real-time communication between a client and a server. In this article, we will explore integrating WebSockets using Go (backend) and React (frontend).
Setting Up the Go WebSocket Server
First, we need to set up a simple WebSocket server using Go. We'll use the popular Gorilla WebSocket package to handle WebSocket connections.
package main
import (
"log"
"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 {
log.Fatal(err)
}
defer ws.Close()
for {
_, msg, err := ws.ReadMessage()
if err != nil {
log.Println(err)
break
}
log.Printf("Received: %s", msg)
}
}
func main() {
http.HandleFunc("/ws", handleConnections)
log.Println("Server started on :8080")
log.Fatal(http.ListenAndServe(":8080", nil))
}
This Go program listens for WebSocket connections on /ws, echoing received messages until the connection closes.
Creating the React Frontend
Next, we create a React application to connect to our Go WebSocket server. We'll use Create React App to simplify starting our frontend project.
npx create-react-app websocket-react-client
cd websocket-react-client
Now, modify the src/App.js file to implement the WebSocket client logic:
import React, { useEffect, useState } from 'react';
function App() {
const [message, setMessage] = useState('');
useEffect(() => {
const socket = new WebSocket('ws://localhost:8080/ws');
socket.onopen = () => {
console.log('WebSocket connection established');
};
socket.onmessage = (event) => {
console.log('Message received: ', event.data);
setMessage(event.data);
};
socket.onclose = () => {
console.log('WebSocket connection closed');
};
return () => {
socket.close();
};
}, []);
return (
WebSocket Client
Received message: {message}
);
}
export default App;
Here, we establish a WebSocket connection to our Go server and display any received messages on the page.
Testing the Integration
With both the Go server and React client set up, you must ensure that the Go server is running. Start your application by running:
go run main.go
And then, start your React application:
npm start
Visit http://localhost:3000 to see the WebSocket connection status and any messages the server might send. Now your React UI should show messages received from the Go WebSocket server.
Conclusion
Integrating WebSockets with Go and React can significantly enhance user experience with real-time data. This foundational setup can be extended for complex communication patterns like chat applications, notifications, and live updates.