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.