Go WebSockets let a server and a browser talk to each other in both directions over one open connection. In this post, you will learn how WebSockets work and when to use them. Then we will build a small chat server where every message reaches every connected user instantly.
Before you start, it helps to know two earlier lessons. You built handlers in the Go HTTP server tutorial, and you protected shared data in the Go sync package lesson. So we use both ideas again here.
What Are Go WebSockets?
In short, a WebSocket is a long-lived, two-way connection between a client and a server. Normal HTTP works like sending letters: the browser asks, the server answers, and the conversation ends. A WebSocket, however, works like a phone call. In contrast, once the line is open, both sides can speak at any time.
However, the Go standard library does not include a WebSocket server. So most Go WebSockets projects use a small, well-tested package. Specifically, this lesson uses github.com/coder/websocket, which follows Go’s own style and supports context everywhere.
Why Go WebSockets Matter
Some apps need data the moment it changes. In that case, waiting for the user to refresh the page is not good enough. For example, here are typical cases.
- Chat apps: when one user sends a message, it must appear for everyone right away.
- Live dashboards: order counts or server health update every second, so the screen must refresh itself.
- Multiplayer games: player moves travel both ways many times per second.
- Collaborative editors: two people type in the same document at the same time.
In short, Go WebSockets fit any feature where both sides need to send messages whenever they like.
How Go WebSockets Work
First, every WebSocket starts life as a normal HTTP request. Then the browser sends a GET request with an Upgrade: websocket header. Then, if the server agrees, it replies with status 101 Switching Protocols. From that moment on, the same TCP connection carries WebSocket frames instead of HTTP.

After the upgrade, each message travels inside a small frame. A frame says whether the data is text or binary, so JSON usually goes as text. Also, either side can send a close frame with a status code to end the call politely.
The Upgrade Request and Response
This table shows the key headers in the handshake. Luckily, you rarely write them yourself, because the package handles them.
| Header | Sent by | Purpose |
|---|---|---|
Upgrade: websocket | Client | Asks to switch protocols |
Connection: Upgrade | Client | Says this connection should change |
Sec-WebSocket-Key | Client | A random value for the handshake |
Sec-WebSocket-Version: 13 | Client | The protocol version |
Sec-WebSocket-Accept | Server | Proves the server understood the key |
Key Parts of a Go WebSockets Server
In practice, a Go WebSockets server has a few clear jobs. So once you see them, the code becomes easy to follow.
Accepting the Connection
To begin with, websocket.Accept upgrades the HTTP request and returns a *websocket.Conn. By default, it also checks the Origin header. As a result, other websites cannot open a socket to your server from a visitor’s browser.
Reading Messages
Next, c.Read(ctx) blocks until the next message arrives. Then it returns the message type, the bytes and an error. When the browser closes the tab, Read returns an error, and your loop ends.
Writing Messages
Similarly, c.Write(ctx, websocket.MessageText, data) sends one message. Because it takes a context, you can give every write a timeout. So one slow client cannot freeze your server.
Closing Cleanly
c.Close(websocket.StatusNormalClosure, "bye") sends a close frame and waits briefly for the other side. On the other hand, c.CloseNow() simply drops the connection. For this reason, a common pattern is defer c.CloseNow() as a safety net.
Go WebSockets vs Polling vs Server-Sent Events
In fact, there are three common ways to get live data into a browser. For instance, the table below compares them.
| Feature | WebSockets | HTTP polling | Server-Sent Events |
|---|---|---|---|
| Direction | Both ways | Client asks again and again | Server to client only |
| Connection | One long-lived | Many short requests | One long-lived |
| Delay | Instant | Up to the poll interval | Instant |
| Server cost | Low per message | High, many wasted requests | Low per message |
| Works through plain HTTP tools | Needs upgrade support | Yes | Yes |
| Best for | Chat, games, editors | Rare, simple checks | Feeds, notifications |
So when should you use which? Choose WebSockets when the browser must also send messages often. If only the server talks, Server-Sent Events are simpler, and we cover them in the next post.
Hands-On: Build a Go WebSockets Chat Server
Now let’s build a chat room with Go WebSockets. Specifically, every message from any user goes to all connected users, including the sender.
Step 1: Create the Project
First, create a module and add the package. Then the go get command records the version in go.mod.
mkdir chat && cd chat
go mod init example.com/chat
go get github.com/coder/websocket
Step 2: The Hub That Tracks Connections
Here, the hub keeps a set of open connections. Many goroutines touch it at once, so a mutex protects the map.
type Hub struct {
mu sync.Mutex
conns map[*websocket.Conn]struct{}
}
func NewHub() *Hub {
return &Hub{conns: make(map[*websocket.Conn]struct{})}
}
func (h *Hub) add(c *websocket.Conn) {
h.mu.Lock()
h.conns[c] = struct{}{}
h.mu.Unlock()
}
func (h *Hub) remove(c *websocket.Conn) {
h.mu.Lock()
delete(h.conns, c)
h.mu.Unlock()
}
func (h *Hub) broadcast(ctx context.Context, msg []byte) {
h.mu.Lock()
defer h.mu.Unlock()
for c := range h.conns {
wctx, cancel := context.WithTimeout(ctx, 5*time.Second)
err := c.Write(wctx, websocket.MessageText, msg)
cancel()
if err != nil {
c.CloseNow()
delete(h.conns, c)
}
}
}
Notice that the map value is an empty struct, because we only care about the keys. Also, each write gets its own five second timeout. Then, if a write fails, the hub drops that connection and moves on.
Step 3: The WebSocket Handler
This handler upgrades the request and registers the connection. After that, it reads messages until the client leaves.
func (h *Hub) serveWS(w http.ResponseWriter, r *http.Request) {
c, err := websocket.Accept(w, r, nil)
if err != nil {
log.Println("accept:", err)
return
}
defer c.CloseNow()
h.add(c)
defer h.remove(c)
log.Println("client connected")
ctx := r.Context()
for {
_, data, err := c.Read(ctx)
if err != nil {
log.Println("client left:", websocket.CloseStatus(err))
return
}
h.broadcast(ctx, data)
}
}
func main() {
hub := NewHub()
http.Handle("/", http.FileServer(http.Dir("static")))
http.HandleFunc("/ws", hub.serveWS)
log.Println("chat server on http://localhost:8080")
log.Fatal(http.ListenAndServe(":8080", nil))
}
As with any HTTP handler, each browser tab gets its own goroutine running serveWS. Also, the two defer lines run when the loop ends, so the hub always forgets closed connections. websocket.CloseStatus returns the close code, or -1 when the error was not a close frame.

Step 4: A Tiny Browser Page
Next, save this file as static/index.html. Specifically, it opens a socket and prints incoming messages. Also, it sends whatever you type.
<input id="msg" placeholder="Type a message">
<button onclick="send()">Send</button>
<ul id="log"></ul>
<script>
const ws = new WebSocket("ws://" + location.host + "/ws");
ws.onmessage = (e) => {
const li = document.createElement("li");
li.textContent = e.data;
document.getElementById("log").appendChild(li);
};
function send() {
const box = document.getElementById("msg");
ws.send(box.value);
box.value = "";
}
</script>
Then open http://localhost:8080 in two browser tabs. When you type “Hello from Asha” in one tab, both tabs show the message at once.
Step 5: A Go Client for Testing
Besides the browser, you can also talk to the server from Go. Indeed, this is handy for tests and command line tools.
func main() {
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
defer cancel()
c, _, err := websocket.Dial(ctx, "ws://localhost:8080/ws", nil)
if err != nil {
log.Fatal(err)
}
defer c.Close(websocket.StatusNormalClosure, "bye")
if err := c.Write(ctx, websocket.MessageText, []byte("Hello from Asha")); err != nil {
log.Fatal(err)
}
_, msg, err := c.Read(ctx)
if err != nil {
log.Fatal(err)
}
fmt.Println("Received:", string(msg))
}
Because the hub also sends messages back to the sender, the client reads its own message. So with the server running, you will see this output.
Received: Hello from Asha
Meanwhile, the server log shows client connected and, after the client closes, client left: StatusNormalClosure.
Scaling Go WebSockets to Many Servers
However, our hub lives in the memory of one Go process. So if you run two servers behind a load balancer, users on server A never see messages from server B. This is the most common surprise when a chat app grows.
Instead, the usual fix is a shared message bus. For example, each server publishes incoming chat messages to a channel in NATS or Redis. Then every server subscribes to that channel and forwards messages to its own local clients. As a result, all users see all messages, no matter which server they joined. We will build exactly this kind of messaging later in this series.
Also, load balancers must support the WebSocket upgrade and long-lived connections. Most modern ones do, but check their idle timeout. Otherwise, quiet connections may close after a minute.
Common Mistakes with Go WebSockets
- Sharing a map without a lock: two goroutines change
connstogether and the program crashes. So always guard shared state with a mutex. - Writing with no timeout: one frozen browser blocks every broadcast. Instead, give each write a context deadline.
- Turning off the origin check:
InsecureSkipVerifylets any website use your socket. Instead, useOriginPatternsfor the domains you trust. - Forgetting the read limit: by default, reads are limited to 32 KB. Call
c.SetReadLimitonly when you truly need bigger messages. - Using plain ws in production: data travels as plain text. Serve the site over HTTPS, so the browser uses
wss://.
Best Practices for Go WebSockets
- Keep one reading goroutine per connection, because the package expects a single reader.
- **Send JSON messages with a
typefield**, so the client can tell chat messages from system events. - Ping idle connections, since proxies often close sockets that stay silent for a minute.
- Limit message size, because huge messages can exhaust server memory.
- Plan for reconnects in the browser, because mobile networks drop connections often.
Practice Task
To practise Go WebSockets, add a username to every message. Send JSON like {"user":"Asha","text":"Hi"} from the browser, decode it in Go and broadcast “Asha: Hi” to everyone.
Hint: the wsjson package inside coder/websocket reads and writes JSON values directly.
Official Resources
These pages give the exact API details and the protocol rules, so check them when you need a specific option.
Quick Recap
- Go WebSockets keep one connection open for two-way messages.
- First of all, every socket starts as an HTTP request that upgrades with status 101.
websocket.Acceptupgrades,Readreceives andWritesends.- Meanwhile, a mutex-protected hub tracks connections and broadcasts messages.
- Give each write a timeout and keep the default origin check.
- Finally, use WebSockets for two-way features and SSE for one-way feeds.
What’s Next?
Go WebSockets are powerful. However, many features only need the server to push updates. Next, we will look at a simpler tool for that job: Server-Sent Events.
Next lesson: Go Server-Sent Events: Live Updates Over HTTP


