Sling Academy
Home/Golang/Integrating WebSockets with Go and React for Real-Time UIs

Integrating WebSockets with Go and React for Real-Time UIs

Last updated: November 26, 2024

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.

Next Article: Creating a Live Chat Support System with WebSockets in Go

Previous Article: Building a Stock Price Tracker Using WebSockets in Go

Series: Websocket & Chat Programs in Go

Golang

Related Articles

You May Also Like

  • How to remove HTML tags in a string in Go
  • How to remove special characters in a string in Go
  • How to remove consecutive whitespace in a string in Go
  • How to count words and characters in a string in Go
  • Relative imports in Go: Tutorial & Examples
  • How to run Python code with Go
  • How to generate slug from title in Go
  • How to create an XML sitemap in Go
  • How to redirect in Go (301, 302, etc)
  • Using Go with MongoDB: CRUD example
  • Auto deploy Go apps with CI/ CD and GitHub Actions
  • Fixing Go error: method redeclared with different receiver type
  • Fixing Go error: copy argument must have slice type
  • Fixing Go error: attempted to use nil slice
  • Fixing Go error: assignment to constant variable
  • Fixing Go error: cannot compare X (type Y) with Z (type W)
  • Fixing Go error: method has pointer receiver, not called with pointer
  • Fixing Go error: assignment mismatch: X variables but Y values
  • Fixing Go error: array index must be non-negative integer constant