How do I broadcast messages to multiple clients in Go?

Learn how to broadcast messages to multiple clients in Go, enabling real-time communication in your applications. This guide provides a clear example and demonstrates the principles you need to implement message broadcasting.
Go, broadcasting messages, multi-client communication, Go WebSockets, real-time applications, Go programming.

package main

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

var clients = make(map[*websocket.Conn]bool) // Connected clients
var broadcast = make(chan string)             // Broadcast channel

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

// Handle connection for each client
func handleConnections(w http.ResponseWriter, r *http.Request) {
    conn, err := upgrader.Upgrade(w, r, nil)
    if err != nil {
        fmt.Println("Error while upgrading connection:", err)
        return
    }
    defer conn.Close()

    clients[conn] = true // Register client

    for {
        var msg string
        err := conn.ReadMessage(&msg)
        if err != nil {
            fmt.Println("Error reading message:", err)
            delete(clients, conn)
            return
        }
        broadcast <- msg // Send message to broadcast channel
    }
}

// Handle incoming messages and broadcast them to all connected clients
func handleMessages() {
    for {
        msg := <-broadcast
        for client := range clients {
            err := client.WriteMessage(websocket.TextMessage, []byte(msg))
            if err != nil {
                fmt.Println("Error broadcasting message:", err)
                client.Close()
                delete(clients, client)
            }
        }
    }
}

func main() {
    http.HandleFunc("/ws", handleConnections)

    go handleMessages()

    fmt.Println("Server started on :8080")
    err := http.ListenAndServe(":8080", nil)
    if err != nil {
        fmt.Println("Error starting server:", err)
    }
}
    

Go broadcasting messages multi-client communication Go WebSockets real-time applications Go programming.