Broadcasting Messages
Send to many clients.
Broadcasting Messages is a free Go Academy lesson on CoddyKit — lesson 3 of 4. You can read the complete lesson below for free — then practise it hands-on in the browser with a built-in code editor and a 24/7 AI tutor. It is part of the Go Academy learning path, one of 4 lessons in the course, and your progress syncs across the web and the CoddyKit app.
Sending to Many Clients
Chat rooms and live feeds need to push a single message to every connected client. Since each WebSocket allows only one writer, you need a coordination pattern: the hub.
The Hub Pattern
A hub is a central goroutine that owns the set of clients and a broadcast channel. Clients register, unregister, and the hub fans messages out. No shared map is touched by multiple goroutines directly.
Hub Data Structures
The hub holds:
- A set of clients (
map[*Client]bool) - A
broadcastchannel of messages registerandunregisterchannels
type Hub struct {
clients map[*Client]bool
broadcast chan []byte
register chan *Client
unregister chan *Client
}The Hub Run Loop
A single Run goroutine selects over the channels. Because only this goroutine mutates the map, no mutex is needed.
func (h *Hub) Run() {
for {
select {
case c := <-h.register:
h.clients[c] = true
case c := <-h.unregister:
delete(h.clients, c)
close(c.send)
case msg := <-h.broadcast:
for c := range h.clients {
c.send <- msg
}
}
}
}Per-Client Send Channel
Each client has a buffered send chan []byte. The hub writes to it; a dedicated writer goroutine drains it to the socket. This respects the one-writer rule.
type Client struct {
conn *websocket.Conn
send chan []byte
}The Writer Goroutine
Each client runs a writePump that ranges over send and writes to the socket. If the channel closes, it sends a close frame.
func (c *Client) writePump() {
for msg := range c.send {
c.conn.WriteMessage(websocket.TextMessage, msg)
}
}Avoiding Slow Clients
If one client is slow, its buffered send fills up. A common policy: if the buffer is full, drop the client rather than block the whole hub.
select {
case c.send <- msg:
default:
close(c.send)
delete(h.clients, c)
}Why Channels Over Mutexes
Go's motto: "share memory by communicating." Funneling all mutations through one goroutine via channels avoids race conditions on the client map without explicit locking.
Broadcasting a Message
Any handler can broadcast by sending on the hub channel; the hub does the fan-out to every registered client.
hub.broadcast <- []byte("server announcement")Targeted vs Broadcast
For rooms or direct messages, store clients keyed by room or user ID and iterate only the relevant subset instead of all clients. This keeps a chat with many rooms efficient.
Runnable: Fan-Out With Channels
This self-contained program models a hub fanning one message out to several client channels using only the standard library and goroutines.
package main
import (
"fmt"
"sync"
)
func main() {
clients := []chan string{make(chan string, 1), make(chan string, 1), make(chan string, 1)}
msg := "hello all"
for _, c := range clients {
c <- msg // fan-out
}
var wg sync.WaitGroup
for i, c := range clients {
wg.Add(1)
go func(id int, ch chan string) {
defer wg.Done()
fmt.Printf("client %d got: %s\n", id, <-ch)
}(i, c)
}
wg.Wait()
}Quick Check
Test your understanding of broadcasting.
Recap
You learned to broadcast to many clients:
- The hub goroutine owns the client set and a broadcast channel
- Each client has a buffered send channel drained by a writer goroutine
- This respects the one-writer-per-connection rule
- Drop slow clients to keep the hub responsive
Frequently asked questions
Is the “Broadcasting Messages” lesson free?
Yes — the full text of “Broadcasting Messages” is free to read here on the web, and the Go Academy course includes 4 lessons in total. To practise it interactively (a built-in code editor and a 24/7 AI tutor) and unlock the rest of the Go Academy course, upgrade to CoddyKit PRO.
What will I learn in “Broadcasting Messages”?
Send to many clients. You practise Go Academy with hands-on code you run directly in the browser, and a 24/7 AI tutor answers your questions as you work through the lesson.
Do I need any experience to start Go Academy?
No prior experience is required. Go Academy on CoddyKit is structured for beginners through advanced learners; this is — lesson 3 of 4, so you can start here or from the beginning and move at your own pace.
How long does the “Broadcasting Messages” lesson take?
Most CoddyKit lessons take about 5–10 minutes. Each one is bite-sized and interactive, so you make steady progress and pick up exactly where you left off across the web and the app.
Can I write and run code in this Go Academy lesson?
Yes. Every Go Academy lesson includes a built-in code editor, so you write and run real code right in your browser and get instant AI feedback — no local setup required.
All lessons in this course
- WebSocket Basics
- Using gorilla/websocket
- Broadcasting Messages
- Connection Management