Creating a Real-Time Notification System with Go

Table of Contents

  1. Introduction
  2. Prerequisites
  3. Setting Up the Environment
  4. Creating the Backend
  5. Creating the Frontend
  6. Testing the Application
  7. Conclusion

Introduction

In this tutorial, we will learn how to create a real-time notification system using Go. We will build a web application that can send and receive notifications instantly to connected users. By the end of this tutorial, you will understand the basics of Go programming, web sockets, and how to create a simple real-time application.

Prerequisites

To follow along with this tutorial, you should have basic knowledge of Go programming language. It is also helpful to have experience with HTML, CSS, and JavaScript for the frontend part. Additionally, make sure you have Go installed on your system.

Setting Up the Environment

Before we start building the application, let’s set up our development environment.

  1. Install Go by downloading the latest stable release from the official website and following the installation instructions for your operating system.

  2. Create a new directory for your project. Open a terminal or command prompt, navigate to the desired location, and run the following command:

    ```shell
    mkdir notification-system
    ```
    
  3. Change into the project directory:

    ```shell
    cd notification-system
    ```
    
  4. Initialize a new Go module:

    ```shell
    go mod init github.com/your-username/notification-system
    ```
    

Creating the Backend

First, let’s create the backend of our real-time notification system.

  1. Create a new Go file named main.go:

    ```shell
    touch main.go
    ```
    
  2. Open main.go in a text editor and import the necessary packages:

    ```go
    package main
    
    import (
    	"fmt"
    	"log"
    	"net/http"
    
    	"github.com/gorilla/websocket"
    )
    ```
    
  3. Declare the variables we will use:

    ```go
    var clients = make(map[*websocket.Conn]bool)
    var broadcast = make(chan Message)
    var upgrader = websocket.Upgrader{}
    ```
    
  4. Define a Message struct to represent notifications:

    ```go
    type Message struct {
    	Text string `json:"text"`
    }
    ```
    
  5. Create a function to handle incoming WebSocket connections:

    ```go
    func handleConnections(w http.ResponseWriter, r *http.Request) {
    	// Upgrade initial GET request to a WebSocket
    	ws, err := upgrader.Upgrade(w, r, nil)
    	if err != nil {
    		log.Fatal(err)
    	}
    
    	// Register new client
    	clients[ws] = true
    }
    ```
    
  6. Create a function to handle incoming messages:

    ```go
    func handleMessages() {
    	for {
    		// Read message from broadcast channel
    		msg := <-broadcast
    
    		// Send message to all clients
    		for client := range clients {
    			err := client.WriteJSON(msg)
    			if err != nil {
    				log.Printf("Error: %v", err)
    				client.Close()
    				delete(clients, client)
    			}
    		}
    	}
    }
    ```
    
  7. Add a main function to start the server and handle connections:

    ```go
    func main() {
    	// Configure WebSocket route
    	http.HandleFunc("/", handleConnections)
    
    	// Start listening for incoming chat messages
    	go handleMessages()
    
    	// Start the server
    	err := http.ListenAndServe(":8080", nil)
    	if err != nil {
    		log.Fatal("Error starting server:", err)
    	}
    }
    ```
    

Creating the Frontend

Next, let’s create the frontend of our real-time notification system.

  1. Create a new HTML file named index.html in the project directory.

  2. Copy the following code into index.html:

    ```html
    <!DOCTYPE html>
    <html lang="en">
    
    <head>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <title>Real-Time Notification System</title>
    </head>
    
    <body>
        <h1>Real-Time Notification System</h1>
        <div id="notification-container">
            <ul id="notification-list"></ul>
        </div>
        <div>
            <input type="text" id="notification-input" placeholder="Enter your notification message">
            <button id="notification-send">Send</button>
        </div>
    
        <script>
            const socket = new WebSocket("ws://localhost:8080/");
    
            socket.onmessage = (event) => {
                const message = JSON.parse(event.data);
                const listItem = document.createElement("li");
                listItem.textContent = message.text;
                document.getElementById("notification-list").appendChild(listItem);
            };
    
            document.getElementById("notification-send").addEventListener("click", () => {
                const input = document.getElementById("notification-input");
                const message = {
                    text: input.value,
                };
                socket.send(JSON.stringify(message));
                input.value = "";
            });
        </script>
    </body>
    
    </html>
    ```
    

Testing the Application

  1. Build the Go application:

    ```shell
    go build
    ```
    
  2. Start the server:

    ```shell
    ./notification-system
    ```
    
  3. Open your web browser and visit http://localhost:8080/. You should see the real-time notification system.

  4. Open multiple browser windows or tabs and try sending notifications. You will notice that each connected client receives the notifications instantly.

Conclusion

Congratulations! You have successfully created a real-time notification system using Go. You learned how to set up the Go development environment, create a backend server using web sockets, and build a simple frontend to send and receive notifications. This tutorial provides a basic foundation that you can expand upon to create more complex real-time applications.