Sling Academy
Home/Golang/Implementing a Real-Time Chat Application Using WebSockets in Go

Implementing a Real-Time Chat Application Using WebSockets in Go

Last updated: November 26, 2024

Creating a real-time chat application can be an excellent project for understanding WebSocket connections. WebSockets allow you to open an interactive session between a client and a server. In this article, we'll walk through the steps required to implement a real-time chat application using the Go programming language.

 

Setting Up the Project

To get started, let's create a new directory for the chat application project:

bash
$ mkdir go-chat
$ cd go-chat

Next, initialize a new Go module:

bash
$ go mod init go-chat

Installing Dependencies

We'll need the gorilla/websocket package for WebSocket support. Install the package with:

bash
$ go get github.com/gorilla/websocket

Creating the WebSocket Server

Now, let's implement a basic WebSocket server that will handle WebSocket connections, messages reception, and broadcasting.

go
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 {
        messageType, message, err := ws.ReadMessage()
        if err != nil {
            fmt.Println(err)
            break
        }
        fmt.Printf("Received: %s\n", message)

        if err := ws.WriteMessage(messageType, message); err != nil {
            fmt.Println(err)
            break
        }
    }
}

func main() {
    fs := http.FileServer(http.Dir("./public"))
    http.Handle("/", fs)
    http.HandleFunc("/ws", handleConnections)

    if err := http.ListenAndServe(":8080", nil); err != nil {
        fmt.Println(err)
    }
}

Frontend: Simple HTML and JavaScript Client

Let's create a simple HTML file with JavaScript to connect to our WebSocket server:

html



    
    Go Chat


    Real-Time Chat
    
    Send
    

    
        const ws = new WebSocket('ws://localhost:8080/ws');

        ws.onmessage = function(event) {
            const messages = document.getElementById('messages');
            const message = document.createElement('li');
            message.textContent = event.data;
            messages.appendChild(message);
        };

        document.getElementById('sendBtn').onclick = function() {
            const messageInput = document.getElementById('message');
            ws.send(messageInput.value);
            messageInput.value = '';
        };
    


Running Your Chat Application

To run your chat application, you'll need to open a terminal and execute:

bash
$ go run .

You can access your chat application by opening a web browser and navigating to http://localhost:8080.

Conclusion

In this tutorial, we covered how to create a simple real-time chat application using Go and WebSockets. This is just the foundation, and you can further enhance it by adding features such as user authentication, private messaging, and chat rooms.

Next Article: Broadcasting Messages to Multiple Clients with WebSockets in Go

Previous Article: Understanding WebSocket Protocols and Upgrades 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