Sling Academy
Home/Golang/Designing a Multi-Room Chat Application with WebSockets in Go

Designing a Multi-Room Chat Application with WebSockets in Go

Last updated: November 26, 2024

Introduction

In this article, we'll explore how to design a multi-room chat application using WebSockets in Go. The multi-room chat feature allows users to join different chat rooms, enhancing the user experience by offering a more organized and topic-specific conversation environment.

Prerequisites

  • Basic understanding of Go programming language
  • Familiarity with WebSockets concept
  • Go environment set up on your machine

Setting up the Go Project

To start, let's create a Go project. Open your terminal and run the following commands:

mkdir chatapp
cd chatapp
go mod init github.com/yourusername/chatapp

Installing the Gorilla WebSocket Package

We'll use the Gorilla WebSocket package, a widely-used toolkit for handling WebSocket protocol in Go. Install it using the command below:

go get github.com/gorilla/websocket

Creating the WebSocket Handler

Now, let's create a WebSocket handler to manage connections and communication:

package main

import (
	"net/http"
	"github.com/gorilla/websocket"
)

var upgrader = websocket.Upgrader{
	CheckOrigin: func(r *http.Request) bool { return true },
}

func wsHandler(w http.ResponseWriter, r *http.Request) {
	conn, err := upgrader.Upgrade(w, r, nil)
	if err != nil {
		http.Error(w, "Could not open websocket connection", http.StatusBadRequest)
		return
	}
	handleMessages(conn)
}

Handling Message Broadcasting

We'll now write the logic to broadcast messages to different chat rooms. For illustration, let's create a basic function. This part will handle multiple clients and ensures real-time communication across rooms.

type Client struct {
	room string
	conn *websocket.Conn
}

type Room struct {
	clients   map[*Client]bool
	broadcast chan []byte
}

func (room *Room) run() {
	for {
		select {
		case message := <-room.broadcast:
			for client := range room.clients {
				client.conn.WriteMessage(websocket.TextMessage, message)
			}
		}
	}
}

// Function to handle messages from clients
func handleMessages(connection *websocket.Conn, roomName string) {
	client := &Client{room: roomName, conn: connection}
	for {
		messageType, message, err := connection.ReadMessage()
		if err != nil {
			return
		}
		broadcastToRoom(client.room, message)
	}
}

func broadcastToRoom(roomName string, message []byte) {
	room := rooms[roomName]
	room.broadcast <- message
}

Initializing and Running the Server

Finally, let's set up our server to use this WebSocket handler to manage connections:

func main() {
	rooms = make(map[string]*Room)
	http.HandleFunc("/ws", wsHandler)
	
	go room.run()

	if err := http.ListenAndServe(":8080", nil); err != nil {
		panic("Error starting the server: " + err.Error())
	}
}

Conclusion

By following these steps, you should have a functional multi-room chat application using WebSockets in Go. Although this is a simplified example, it can be expanded with features like persistent storage and authentication to make a more comprehensive system.

Next Article: Optimizing WebSocket Performance for High-Load Applications in Go

Previous Article: Working with JSON Messages Over 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