Skip to main content

What Are WebSockets? A Comprehensive Go Tutorial for Building Your Own from Scratch

Updated 29 min readMarkdown
What Are WebSockets? A Comprehensive Go Tutorial for Building Your Own from Scratch

Introduction

In modern system architecture, building real-time, low-latency communication channels between clients and backend servers is crucial. Traditionally, if your web application needed live updates whether a new chat message, a multiplayer game move, or a live stock tick it had to rely on constant HTTP polling. This continuous cycle of opening connections to ask "Any new updates? How about now?" wastes massive amounts of bandwidth, burns CPU cycles on repeated TCP/TLS handshakes, and introduces unnecessary latency.

Enter WebSockets.

A WebSocket serves as a persistent, bidirectional communication tunnel that upgrades a standard HTTP request into a live, full-duplex connection over a single TCP socket. Instead of the client repeatedly pulling data or the server spinning up a brand-new connection for every push, both the client and server can stream lightweight messages to each other simultaneously at any moment. Whether you're powering collaborative tools like Figma, real-time messaging platforms, or live financial dashboards, WebSockets ensure your applications remain instantaneous, lightweight, and deeply interactive.

In this blog we will skip third-party packages and build an RFC 6455-compliant server completely from scratch using nothing but Go's standard library.


How does it work?

In a standard HTTP setup, a client sends a request, waits for a response, and the connection closes (or sits idle waiting for the next client-initiated request). In a WebSocket-enabled setup, the connection goes through a protocol upgrade lifecycle:

  1. The Opening Handshake (HTTP Upgrade): The client initiates a standard HTTP GET request containing special upgrade headers (Connection: Upgrade, Upgrade: websocket) along with a randomly generated base64 nonce (Sec-WebSocket-Key).
  2. Cryptographic Verification & Switching Protocols: The server validates the headers, concatenates the client's key with a hardcoded RFC 6455 magic GUID, computes a SHA-1 hash encoded in Base64, and replies with an HTTP/1.1 101 Switching Protocols status code.
  3. Socket Hijacking: Instead of closing the connection after sending the 101 response, the server takes direct ownership of the underlying raw TCP socket.
  4. Full-Duplex Binary Framing: HTTP is now completely out of the picture. Both client and server exchange lightweight binary data frames independently and simultaneously over the same open wire.
  5. Graceful Teardown: When either party is ready to disconnect, it sends a dedicated Close control frame (0x8), allowing both sides to cleanly release network descriptors and background goroutines.

By upgrading a single connection once and shifting to raw binary framing, WebSockets eliminate per-message HTTP header bloat, remove connection-setup overhead, and unlock true real-time two-way streaming.


Understanding WebSockets: A Walkie-Talkie vs. Phone Call Analogy

To understand why WebSockets feel so fundamentally different from traditional REST APIs, let's compare how two people communicate using a walkie-talkie versus an open phone call. In this scenario:

  • The Caller is the Client (Browser),
  • The Receiver is your Server,
  • Dialing & Saying "Hello" is the HTTP Upgrade Handshake,
  • The Open Line is the hijacked TCP socket.

The Half-Duplex Walkie-Talkie (Traditional HTTP)

Imagine trying to have a fast-paced conversation over a pair of walkie-talkies. To say anything, you have to hold down the push-to-talk button, state your callsign and channel frequency (sending heavy HTTP headers), ask your question, say "Over", and release the button.

While you are speaking, the other person cannot interrupt or push updates to you. If you want to know whether anything changed two seconds later, you have to press the button, state your callsign all over again, and ask. It works great for occasional, turn-based commands but for real-time conversation, it is slow, repetitive, and strictly half-duplex.

The Full-Duplex Open Phone Call (WebSockets)

Now consider picking up a phone and dialing your friend. You go through the setup ritual only once: you dial the number, it rings, and your friend picks up and says "Hello" (HTTP/1.1 101 Switching Protocols).

From that exact second onward, the dialing phase is over. Both of you have an open microphone and an open earpiece running simultaneously. You don't have to re-dial or state your name before every sentence you can talk while your friend is talking, your friend can blurt out breaking news without you asking first, and the line stays alive until one of you hangs up.

Let's stop pressing the walkie-talkie button and wire up our own WebSocket engine in Go!


Guide to Wiring Up a Full-Duplex WebSocket Engine in Go

We will leverage Go’s highly optimized native standard library to develop a completely self-contained WebSocket server from scratch, just raw TCP sockets, bitwise math, and Go channels.

To keep the build clean and incremental, we will structure our implementation across 4 core milestones (plus a Bonus Milestone 5 for readers who stick around to build private 1-on-1 direct messaging):

  1. Milestone 1 (The Opening Handshake): Validate WebSocket upgrade headers, compute the SHA-1/Base64 cryptographic proof, and hijack the raw TCP socket.
  2. Milestone 2 (Binary Frame Decoding): Parse incoming 2-byte headers, decode variable payload lengths, and unscramble browser messages using 4-byte XOR unmasking.
  3. Milestone 3 (Full-Duplex Read/Write Pumps): Spin up concurrent goroutines to serialize and flush unmasked outbound frames back to the browser.
  4. Milestone 4 (The Single-Owner Connection Hub): Coordinate multiple concurrent clients in a group chat room using Go channels and non-blocking select statements instead of mutex locks.
  5. Bonus Milestone 5 (Routed 1-on-1 DMs): Upgrade our message payloads to structured JSON envelopes so users can send private direct messages ({"to": "bob", "text": "..."}) alongside public broadcasts.

Throughout this tutorial, we won't just look at the final scripts we will dissect the design choices, avoid subtle wire-protocol traps, and verify everything live in our browser console.


Project Setup:

Start by creating a new directory for your WebSocket server, initializing a Go module, and creating main.go:

mkdir websocket
cd websocket
go mod init websocket
touch main.go

Milestone 1: The Opening Handshake & Socket Hijacking

To understand the engineering behind WebSockets, we start at the front door, the HTTP Upgrade Handshake. When a browser executes new WebSocket("ws://localhost:3333/ws"), it doesn't immediately send raw WebSocket binary frames. Instead, it sends a standard HTTP GET request containing four critical headers:

• Upgrade: websocket

• Connection: Upgrade

• Sec-WebSocket-Version: 13

• Sec-WebSocket-Key: A random base64-encoded nonce generated by the browser.

To prove to the browser that our server actually speaks the WebSocket protocol (and isn't just a standard HTTP server blindly echoing headers), RFC 6455 requires us to take that Sec-WebSocket-Key, append a hardcoded magic GUID, hash the combined string with SHA-1, and encode the 20-byte digest in Base64 inside the Sec-WebSocket-Accept response header.

The Hijacker & The Raw \r\n\r\n Trap

Normally in Go, as soon as an http.HandlerFunc returns, net/http automatically closes or recycles the underlying TCP connection. To keep the line open forever, we type-assert http.ResponseWriter to http.Hijacker and call hj.Hijack(). This hands us direct ownership of the raw net.Conn and its buffered reader/writer (*bufio.ReadWriter). Watch out for two subtle traps here:

  1. Strict HTTP Line Endings:
    Because we are writing the raw HTTP 101 Switching Protocols response directly onto the TCP buffer, every header line must end with \r\n (CRLF) not \n with no leading spaces before header names, and the header block must terminate with a blank line (\r\n\r\n). eg:
    Broken (Browser hangs & fails handshake):

    // Missing \r\n, leading spaces before headers, and no trailing blank line
    "HTTP/1.1 101 Switching Protocols \n Upgrade: websocket \n Sec-WebSocket-Accept: %s \r\n"
    

    Valid (Strict RFC 7230 / HTTP/1.1):

    // Exact \r\n per header + \r\n\r\n to signal end of headers
    "HTTP/1.1 101 Switching Protocols\r\nUpgrade: websocket\r\nConnection: Upgrade\r\nSec-WebSocket-Accept: %s\r\n\r\n"
    
  2. Always read from bufrw, not conn:
    When hj.Hijack() returns (conn, bufrw, err), net/http has already wrapped conn inside bufrw's internal buffer.

    • What goes wrong if you read from conn: Suppose a fast client sends its HTTP GET /ws upgrade request and its first 7-byte "hello" frame inside the exact same TCP packet. net/http reads the whole packet into bufrw while parsing the HTTP headers. If your WebSocket reader later calls io.ReadFull(conn, header), those first 7 bytes are stuck inside bufrw's RAM buffer meaning conn misses the frame header, reads mid-payload bytes as headers, and corrupts the stream!
    • The fix: Always read and write exclusively through bufrw (io.ReadFull(c.bufrw, header)).\

Open main.go and add our Milestone 1 handshake server (ending with an empty select {} for now just to keep the socket alive while we test the upgrade):

package main

import (
	"crypto/sha1"
	"encoding/base64"
	"errors"
	"fmt"
	"log"
	"net/http"
	"os"
	"strings"
)

const websocketMagicGUID = "258EAFA5-E914-47DA-95CA-C5AB0DC85B11"

func validateHeaders(h http.Header) (string, int) {
	upgrade := h.Get("Upgrade")
	if upgrade == "" {
		return "Missing Upgrade header", http.StatusBadRequest
	}
	connection := h.Get("Connection")
	if connection == "" {
		return "Missing Connection header", http.StatusBadRequest
	}
	webSecVer := h.Get("Sec-WebSocket-Version")
	if webSecVer == "" {
		return "Missing WebSocket-Version header", http.StatusBadRequest
	}
	webSecKey := h.Get("Sec-WebSocket-Key")
	if webSecKey == "" {
		return "Missing WebSocket-Key header", http.StatusBadRequest
	}
	if !strings.EqualFold(upgrade, "websocket") ||
		!strings.Contains(strings.ToLower(connection), "upgrade") ||
		webSecVer != "13" ||
		strings.TrimSpace(webSecKey) == "" {
		return "Connection cannot be upgraded. Please fix the missing/incorrect headers.", http.StatusBadRequest
	}
	return "", 0
}

func handleUpgradeRequest(w http.ResponseWriter, r *http.Request) {
	if r.Method != http.MethodGet {
		http.Error(w, "Method not allowed", http.StatusMethodNotAllowed)
		return
	}

	h := r.Header
	errorString, errorCode := validateHeaders(h)
	if errorString != "" {
		http.Error(w, errorString, errorCode)
		return
	}

	// Calculating the Return Proof
	magicString := h.Get("Sec-WebSocket-Key") + websocketMagicGUID
	hash := sha1.Sum([]byte(magicString))
	encodedHash := base64.StdEncoding.EncodeToString(hash[:])

	// Upgrade the ResponseWriter to Hijack the connection
	hj, ok := w.(http.Hijacker)
	if !ok {
		http.Error(w, "Webserver doesn't support hijacking", http.StatusInternalServerError)
		return
	}
	conn, bufrw, err := hj.Hijack()
	if err != nil {
		http.Error(w, err.Error(), http.StatusInternalServerError)
		return
	}
	defer conn.Close()

	// Manually writing the raw HTTP 101 Switching Protocols response
	response := fmt.Sprintf(
		"HTTP/1.1 101 Switching Protocols\r\nUpgrade: websocket\r\nConnection: Upgrade\r\nSec-WebSocket-Accept: %s\r\n\r\n",
		encodedHash)
	if _, err := bufrw.WriteString(response); err != nil {
		log.Printf("[%s] Error writing handshake response: %v", conn.RemoteAddr(), err)
		return
	}
	if err := bufrw.Flush(); err != nil {
		log.Printf("[%s] Error flushing handshake response: %v", conn.RemoteAddr(), err)
		return
	}
	log.Printf("[%s] WebSocket handshake completed", conn.RemoteAddr())

	// Keep the hijacked connection open for Milestone 1 verification
	select {}
}

func main() {
	fmt.Println("Starting the server....")
	mux := http.NewServeMux()
	mux.HandleFunc("/ws", handleUpgradeRequest)
	err := http.ListenAndServe(":3333", mux)

	if errors.Is(err, http.ErrServerClosed) {
		fmt.Printf("server closed\n")
	} else if err != nil {
		fmt.Printf("error starting server: %s\n", err)
		os.Exit(1)
	}
}

Check-Point : Testing Milestone 1

Testing the Handshake in Chrome Dev-Tools. Start your server (go run main.go), open any browser tab, open DevTools -> Console, and run:

let ws = new WebSocket("ws://localhost:3333/ws");

Check two things to verify the upgrade succeeded:

  1. Terminal Log: You should see WebSocket handshake completed printed in your Go console.
  2. Browser State: Run ws.readyState in DevTools it should return 1 (OPEN), and the Network tab will show /ws with status 101 Switching Protocols. (Note: Because handleUpgradeRequest is currently paused at select {}, calling ws.send("hello") won't print anything yet)

Time to unpack the binary wire protocol!


Milestone 2: Unpacking Binary Frames & XOR Unmasking

Now that the phone line is open, HTTP is completely gone. Everything traveling over bufrw from this point onward is a stream of raw WebSocket Binary Frames (defined in RFC 6455).

Because TCP is a continuous river of bytes with no built-in "end of message" delimiter, every WebSocket frame starts with a compact binary header telling our server what kind of frame arrived and how many exact bytes to read next.

Anatomy of a Client-to-Server WebSocket Frame:

Let's break down the four moving parts we decode inside client.go:

  1. Byte 0 (FIN bit & Opcode):
    • FIN (header & 0x80):
    - Tells us whether this frame is a complete standalone message (1) or split across multiple continuation chunks (0).

    • Opcode (header & 0x0F):
    - Identifies the frame type: 0x1 (Text), 0x2 (Binary), 0x8 (Close), 0x9 (Ping), or 0xA (Pong).
  2. Byte 1 & The Base-256 Length Odometer (0–125, 126, 127):
    • MASK (header & 0x80):
    - RFC 6455 mandates that all frames sent from a browser must be masked (1). If a client sends an unmasked frame, we immediately reject it as a protocol violation.

    • 7-Bit Payload Length (header & 0x7F):
    - Rather than wasting 8 bytes on every tiny "hi" message, WebSockets cram the length into 7 bits (0 to 127):

    • 0 to 125:
    - That number is the exact byte length of the payload.

    • 126 (Signpost #1):
    - Means "The message is between 126 and 65,535 bytes read the next 2 bytes as a Big-Endian uint16 for the real length." Think of a 2-byte uint16 like a base-256 odometer: a 300-byte message overflows 256 once with 44 left over ([0x01, 0x2C] -> (1 × 256) + 44 = 300).

    • 127 (Signpost #2):
    - Means "The message is over 65 KB read the next 8 bytes as a Big-Endian uint64 for the real length."
  3. 4-Byte Masking-Key & XOR Unscrambling (^):
    • To prevent malicious browser scripts from crafting WebSocket payloads that trick older HTTP proxies into cache poisoning, browsers generate 4 random bytes (maskKey) per frame and scramble the payload using bitwise XOR.

    • Because XOR is its own inverse ((A ^ K) ^ K == A), our server simply runs payload[i] ^= maskKey[i%4] to unscramble the message back into plain text.
  4. OOM Protection (maxPayloadSize):
    • Before calling make([]byte, payloadLength), we enforce a strict 10 MB cap (maxPayloadSize). Without this check, a forged header claiming a uint64 length of several terabytes would trigger an instant Out-Of-Memory crash.

Debugging Story: The 1-Byte Stream Alignment Trap

While building this parser, a tiny mistake taught me how unforgiving raw TCP byte streams are. When decoding a 5-byte "hello" frame, header[1] & 0x7F already gives the integer 5. By accidentally taking the string length of that number (len(strconv.FormatUint(rawPayload, 10))), my parser calculated a payload length of 1 instead of 5.
• It read only "h" (1 byte), leaving "ello" sitting in the TCP buffer.
• On the next loop iteration, "el" was misread as the 2-byte frame header of the next message throwing the entire byte stream out of alignment and printing garbled symbols ("h", "", "ll") before dropping the connection.


Lesson learned: Always use io.ReadFull with exact byte counts if you miscalculate by even a single byte, every subsequent frame on that socket becomes unreadable.

Create client.go in your project root and add our Client struct, readFrame(), and readLoop():

package main

import (
	"bufio"
	"encoding/binary"
	"errors"
	"fmt"
	"io"
	"log"
	"net"
)

const maxPayloadSize = 10 * 1024 * 1024

type Client struct {
	conn  net.Conn
	bufrw *bufio.ReadWriter
}

func (c *Client) readFrame() (opCode byte, payload []byte, err error) {
	header := make([]byte, 2)
	_, err = io.ReadFull(c.bufrw, header)
	if err != nil {
		return 0, nil, err
	}

	// FinBit -> Is this the complete message, or split into chunks?
	// Opcode -> What kind of message is this? (0x1 Text, 0x8 Close, 0x9 Ping, etc.)
	_, opCode = (header[0] & 0x80), (header[0] & 0x0F)
	maskBit, payloadLength := (header[1] & 0x80), int(uint64(header[1]&0x7F))
	if maskBit == 0 {
		return 0, nil, fmt.Errorf("protocol violation: received unmasked client frame (opcode=0x%x)", opCode)
	}
	if opCode == 0x8 {
		return opCode, nil, nil
	}

	if payloadLength > 0 && payloadLength <= 125 {
		// Small message: payloadLength already holds the exact byte count
	} else if payloadLength == 126 {
		// Message is 126 to 65,535 bytes: read the next 2 bytes for the real length
		ext := make([]byte, 2)
		_, err = io.ReadFull(c.bufrw, ext)
		if err != nil {
			return 0, nil, err
		}
		payloadLength = int(uint64(binary.BigEndian.Uint16(ext)))
	} else if payloadLength == 127 {
		// Message is over 65 KB: read the next 8 bytes for the real length
		ext := make([]byte, 8)
		_, err = io.ReadFull(c.bufrw, ext)
		if err != nil {
			return 0, nil, err
		}
		payloadLength = int(binary.BigEndian.Uint64(ext))
	}

	maskKey := make([]byte, 4)
	_, err = io.ReadFull(c.bufrw, maskKey)
	if err != nil {
		return 0, nil, err
	}

	if payloadLength > maxPayloadSize {
		return 0, nil, fmt.Errorf("frame rejected: payload size (%d bytes) exceeds maximum allowed (%d bytes)", payloadLength, maxPayloadSize)
	}

	payload = make([]byte, payloadLength)
	_, err = io.ReadFull(c.bufrw, payload)
	if err != nil {
		return 0, nil, err
	}

	for i := 0; i < len(payload); i++ {
		payload[i] ^= maskKey[i%4]
	}

	return opCode, payload, nil
}

func (c *Client) readLoop() {
	for {
		opCode, payload, err := c.readFrame()
		if err != nil {
			if errors.Is(err, io.EOF) {
				log.Printf("[%s] Client disconnected abruptly (EOF)", c.conn.RemoteAddr())
			} else {
				log.Printf("[%s] Error reading frame: %v", c.conn.RemoteAddr(), err)
			}
			return
		}
		if opCode == 0x8 {
			log.Printf("[%s] Client initiated WebSocket close (opcode=0x8)", c.conn.RemoteAddr())
			return
		}
		log.Printf("[%s] Received frame (opcode=0x%x, len=%d): %s", c.conn.RemoteAddr(), opCode, len(payload), string(payload))
	}
}

Then, inside handleUpgradeRequest in main.go, replace the temporary select {} block with our new Client reader loop:

	// Start streaming incoming frames
	client := &Client{conn: conn, bufrw: bufrw}
	client.readLoop()

Now our server can decode incoming messages from the browser and print them cleanly to the terminal but the phone call is still one-way!

Check-Point : Testing Milestone 2

Testing Frame Decoding & Unmasking. Because our code is now split across main.go and client.go, run the entire package directory:

go run .

Reconnect in your browser's DevTools Console and send a message:

let ws = new WebSocket("ws://localhost:3333/ws");
ws.send("hello from browser!");

Watch your Go terminal you should immediately see your server decode the binary frame, unscramble the XOR mask, and print:

Received frame (opcode=0x1, len=19): hello from browser!

Bonus check: Try sending a string longer than 130 characters like "a".repeat(200) to verify your 2-byte 126 extended-length header parses cleanly too!

Next, let's give our server a voice by building an outbound frame encoder and running a concurrent writer goroutine.


Milestone 3: Going Full-Duplex with Concurrent Read/Write Pumps

Right now, our server is just listening it can unpack incoming frames from the browser, but it cannot talk back. To complete the open phone call, we need an outbound frame encoder and a dedicated writer goroutine.

Why Two Separate Loops? (Avoiding Deadlocks)

In a full-duplex WebSocket connection, reading and writing happen completely independently:

  • If we tried to handle reading and writing inside a single sequential for loop, our server would block on io.ReadFull waiting for the client to speak meaning it could never push unprompted updates to the client until the client sent a message first.
  • Furthermore, bufio.ReadWriter is not safe for concurrent writes. By routing all outbound messages through a buffered Go channel (send chan []byte) drained exclusively by a single writeLoop() goroutine, we guarantee that outbound frames never interleave bytes on the wire.

Server-to-Client Framing Rules

Encoding an outbound frame in writeFrame() is the exact mirror of readFrame(), with two key differences:

  1. Servers NEVER mask outbound frames: While browsers must scramble every frame they send, RFC 6455 strictly forbids servers from masking frames. Because our payload length bytes (0–127) always have their leftmost bit (bit 7) set to 0, the MASK bit is automatically 0, and we omit the 4-byte masking key completely.
  2. Always Flush() the buffer: Writing bytes to c.bufrw puts them in user-space memory. Calling c.bufrw.Flush() immediately forces those bytes out onto the TCP network socket.

Two Concurrency Traps to Avoid

  1. Goroutine Startup Order: Always launch go client.writeLoop() before calling client.readLoop(). Because readLoop() runs a blocking infinite for loop on the handler's goroutine, placing go client.writeLoop() after it means the writer never starts and c.send never drains!
  2. Channel Ownership (defer close(c.send)): Because readLoop() is the sole producer pushing messages into c.send, it owns closing c.send via defer close(c.send). The instant a client disconnects, c.send closes, causing for payload := range c.send in writeLoop() to exit cleanly with zero leaked goroutines.

Update client.go to add the send channel, writeFrame(), and writeLoop():

type Client struct {
	conn  net.Conn
	bufrw *bufio.ReadWriter
	send  chan []byte
}

func (c *Client) readLoop() {
	defer close(c.send)
	for {
		opCode, payload, err := c.readFrame()
		if err != nil {
			if errors.Is(err, io.EOF) {
				log.Printf("[%s] Client disconnected abruptly (EOF)", c.conn.RemoteAddr())
			} else {
				log.Printf("[%s] Error reading frame: %v", c.conn.RemoteAddr(), err)
			}
			return
		}
		if opCode == 0x8 {
			log.Printf("[%s] Client initiated WebSocket close (opcode=0x8)", c.conn.RemoteAddr())
			return
		}
		log.Printf("[%s] Received frame (opcode=0x%x, len=%d): %s", c.conn.RemoteAddr(), opCode, len(payload), string(payload))

		// Queue text frames onto c.send to echo back
		if opCode == 0x1 {
			c.send <- payload
		}
	}
}

func (c *Client) writeFrame(opCode byte, payload []byte) error {
	// Set FIN = 1 + opcode (0x1 for Text, 0xA for Pong)
	header := []byte{0x80 | opCode}

	// Encode payload length (MASK bit is automatically 0 for server frames)
	if len(payload) <= 125 {
		header = append(header, byte(len(payload)))
	} else if len(payload) <= 65535 {
		ext := make([]byte, 2)
		binary.BigEndian.PutUint16(ext, uint16(len(payload)))
		header = append(header, 126)
		header = append(header, ext...)
	} else {
		ext := make([]byte, 8)
		binary.BigEndian.PutUint64(ext, uint64(len(payload)))
		header = append(header, 127)
		header = append(header, ext...)
	}

	if _, err := c.bufrw.Write(header); err != nil {
		log.Printf("[%s] Error writing frame header (opcode=0x%x): %v", c.conn.RemoteAddr(), opCode, err)
		return err
	}
	if _, err := c.bufrw.Write(payload); err != nil {
		log.Printf("[%s] Error writing frame payload (len=%d): %v", c.conn.RemoteAddr(), len(payload), err)
		return err
	}
	if err := c.bufrw.Flush(); err != nil {
		log.Printf("[%s] Error flushing outbound frame: %v", c.conn.RemoteAddr(), err)
		return err
	}
	return nil
}

func (c *Client) writeLoop() {
	for payload := range c.send {
		if err := c.writeFrame(0x1, payload); err != nil {
			log.Printf("[%s] Write loop terminating due to write error: %v", c.conn.RemoteAddr(), err)
			return
		}
	}
}

Next, update handleUpgradeRequest in main.go to initialize the buffered send channel and spawn writeLoop() before blocking on readLoop():

	client := &Client{
		conn:  conn,
		bufrw: bufrw,
		send:  make(chan []byte, 256),
	}

	// Start the writer goroutine FIRST so it drains client.send concurrently
	go client.writeLoop()

	// Block on readLoop in the current handler goroutine
	client.readLoop()

Check-Point : Testing Milestone 3

Restart your server (go run .), open your browser's DevTools Console, and attach an onmessage listener:

let ws = new WebSocket("ws://localhost:3333/ws");
ws.onmessage = (event) => console.log("Server said:", event.data);
ws.send("hello from browser!");

You will immediately see Server said: hello from browser! printed back in the browser console.

Note: Want to prove the connection is truly full-duplex*? Temporarily drop a* time.Tick(2 * time.Second) goroutine right before client.readLoop() that pushes client.send <- []byte("Server push: ping without you asking!"), you'll watch your server stream unprompted messages every 2 seconds even without calling ws.send()!
Just remember to remove that test ticker before moving to Milestone 4.


Milestone 4: The Single-Owner Connection Hub

Right now, each connected user is trapped in their own private echo loop, Tab A can talk to the server, and Tab B can talk to the server, but they cannot talk to each other.

To build a multi-user chat room, we introduce a central Hub (hub.go) that tracks every active connection (map[*Client]bool) and fans out incoming messages to everyone in the room.

Concurrency Design: Channels Over Mutexes & Slow-Consumer Eviction

Instead of protecting the clients map with sync.Mutex locks across dozens of client goroutines, we follow Go's core concurrency proverb: "Share memory by communicating."

  1. Single-Owner Event Loop: Only one dedicated goroutine ever reads or modifies the clients map via three channels: register, unregister, and broadcast.
  2. Race-Free Channel Closing: Notice we move close(client.send) out of readLoop() and into the Hub's unregister handler. If readLoop() closed client.send at the exact millisecond the Hub tried to broadcast to it, Go would panic with send on closed channel. Having the Hub own both sending and closing eliminates that race condition completely.
  3. Non-Blocking Backpressure (select + default): If one client loses internet or freezes in a debugger, its 256-message send buffer eventually fills up. Using a non-blocking select ensures the Hub immediately evicts that stuck client rather than freezing message delivery for the entire room.

Create hub.go in your project root and add the Hub coordinator:

package main

import "log"

type Hub struct {
	clients    map[*Client]bool // Active connected clients
	register   chan *Client     // Newly handshaked clients
	unregister chan *Client     // Disconnecting clients
	broadcast  chan []byte      // Inbound messages to fan out to everyone
}

func newHub() *Hub {
	return &Hub{
		clients:    make(map[*Client]bool),
		register:   make(chan *Client),
		unregister: make(chan *Client),
		broadcast:  make(chan []byte),
	}
}

func (h *Hub) run() {
	for {
		select {
		case client := <-h.register:
			h.clients[client] = true
			log.Printf("[%s] Client joined hub (active clients: %d)", client.conn.RemoteAddr(), len(h.clients))

		case client := <-h.unregister:
			if _, ok := h.clients[client]; ok {
				delete(h.clients, client)
				close(client.send)
				log.Printf("[%s] Client left hub (active clients: %d)", client.conn.RemoteAddr(), len(h.clients))
			}

		case message := <-h.broadcast:
			log.Printf("Broadcasting message (%d bytes) to %d clients", len(message), len(h.clients))
			for client := range h.clients {
				select {
				case client.send <- message:
				default:
					// Client send buffer is full: evict slow consumer so the Hub never stalls
					delete(h.clients, client)
					close(client.send)
					log.Printf("[%s] Evicting slow client: outbound send buffer full (active clients: %d)", client.conn.RemoteAddr(), len(h.clients))
				}
			}
		}
	}
}

Next, make two surgical updates in client.go so Client routes incoming text frames to c.hub.broadcast and unregisters on disconnect:

type Client struct {
	// ... (Existing conn, bufrw, send fields) ...
	hub *Hub
}

func (c *Client) readLoop() {
	// Hand cleanup back to the Hub instead of closing c.send directly
	defer func() {
		c.hub.unregister <- c
	}()

	for {
		// ... (Existing readFrame and 0x8 Close handling) ...

		// Forward incoming text frames to the Hub instead of echoing locally
		if opCode == 0x1 {
			c.hub.broadcast <- payload
		}
	}
}

Finally, wire the shared hub instance into main.go so all incoming connections join the same room:

func handleUpgradeRequest(hub *Hub, w http.ResponseWriter, r *http.Request) {
	// ... (Existing header validation, SHA-1 proof, Hijack, and 101 Flush) ...

	client := &Client{
		conn:  conn,
		bufrw: bufrw,
		send:  make(chan []byte, 256),
		hub:   hub,
	}
	hub.register <- client

	go client.writeLoop()
	client.readLoop()
}

func main() {
	fmt.Println("Starting the server....")
	hub := newHub()
	go hub.run()

	mux := http.NewServeMux()
	mux.HandleFunc("/ws", func(w http.ResponseWriter, r *http.Request) {
		handleUpgradeRequest(hub, w, r)
	})
	// ... (Existing http.ListenAndServe) ...
}

Check-Point: Testing Multi-Tab Group Chat

Restart your server (go run .), open two separate browser tabs (Tab A and Tab B), and connect both in DevTools Console:

let ws = new WebSocket("ws://localhost:3333/ws");
ws.onmessage = (e) => console.log("Room message:", e.data);

Now run ws.send("Hey from Tab A!") in Tab A and watch it appear instantaneously in both Tab A and Tab B!


Bonus Milestone 5: Routed 1-on-1 DMs & Thread-Safe Ping/Pong

For readers who stuck with us this far, let's level up our group broadcast room into a full application-level messaging router supporting private 1-on-1 direct messages and RFC-compliant Ping/Pong heartbeats still using zero external dependencies.

Three Architectural Upgrades

  1. Identity at Handshake (?userId=...): We extract a userId query parameter during the HTTP upgrade (ws://localhost:3333/ws?userId=alice) and index our Hub's registry by username (map[string]*Client) instead of pointer address.
  2. Structured JSON Envelopes & Anti-Spoofing: Instead of broadcasting raw strings, clients send JSON objects ({"to": "bob", "text": "hey"}). When readLoop() unmarshals the payload, it overwrites msg.From = c.userId on the server so clients can never forge messages on someone else's behalf.
  3. Thread-Safe outboundFrame (The Single-Lane Bridge): Earlier, c.send carried raw []byte and writeLoop() hardcoded opcode 0x1 (Text). If readLoop() tried calling c.writeFrame(0xA, payload) directly when a browser sent a 0x9 Ping frame, two goroutines would write to c.bufrw at the same time corrupting the TCP stream. Wrapping {opCode, payload} inside an outboundFrame struct keeps writeLoop() as the sole writer on the socket.


Updating client.go (JSON Parsing & outboundFrame):

type Client struct {
	// ... (Existing conn, bufrw, hub fields) ...
	send   chan outboundFrame
	userId string
}

type Message struct {
	From string `json:"from,omitempty"`
	To   string `json:"to,omitempty"` // Empty = room broadcast; non-empty = private DM
	Text string `json:"text"`
}

type outboundFrame struct {
	opCode  byte
	payload []byte
}

func (c *Client) readLoop() {
	// ... (Existing defer unregister and readFrame loop) ...

		// Queue Pong (0xA) safely through c.send instead of writing directly in readLoop
		if opCode == 0x9 {
			c.send <- outboundFrame{opCode: 0xA, payload: payload}
			continue
		}

		if opCode == 0x1 {
			var msg Message
			if err := json.Unmarshal(payload, &msg); err != nil {
				log.Printf("[%s | user=%s] Invalid JSON payload: %v", c.conn.RemoteAddr(), c.userId, err)
				continue
			}
			msg.From = c.userId // Stamp sender identity on the server
			c.hub.broadcast <- &msg
		}
	}
}

func (c *Client) writeLoop() {
	for frame := range c.send {
		if err := c.writeFrame(frame.opCode, frame.payload); err != nil {
			log.Printf("[%s] Write loop terminating due to write error: %v", c.conn.RemoteAddr(), err)
			return
		}
	}
}


Updating hub.go (DM Routing & Offline System Replies):

In Hub, we change clients to map[string]*Client and broadcast to chan *Message. Inside run(), we branch on message.To != "" to route private DMs directly to target.send (or reply with a "System" offline notice if the recipient isn't connected):

type Hub struct {
	clients    map[string]*Client
	register   chan *Client
	unregister chan *Client
	broadcast  chan *Message
}

// ... (newHub updated to initialize map[string]*Client and chan *Message) ...

func (h *Hub) run() {
	for {
		select {
		case client := <-h.register:
			// Clean up any stale session if the same userId reconnects
			if oldClient, exists := h.clients[client.userId]; exists {
				close(oldClient.send)
			}
			h.clients[client.userId] = client
			log.Printf("[%s | user=%s] Client joined hub (active clients: %d)", client.conn.RemoteAddr(), client.userId, len(h.clients))

		case client := <-h.unregister:
			existing, ok := h.clients[client.userId]
			if ok && existing == client {
				log.Printf("[%s | user=%s] Client left hub (active clients: %d)", client.conn.RemoteAddr(), client.userId, len(h.clients))
				delete(h.clients, client.userId)
				close(client.send)
			}

		case message := <-h.broadcast:
			outBytes, err := json.Marshal(message)
			if err != nil {
				log.Printf("Failed to marshal message from '%s': %v", message.From, err)
				continue
			}

			if message.To != "" {
				target, ok := h.clients[message.To]
				if !ok {
					// Recipient is offline: notify the sender
					log.Printf("DM undelivered: recipient '%s' is offline (sender='%s')", message.To, message.From)
					sysMsg := Message{
						From: "System",
						Text: fmt.Sprintf("User '%s' is offline", message.To),
					}
					sysBytes, err := json.Marshal(sysMsg)
					if err != nil {
						continue
					}
					if sender, exists := h.clients[message.From]; exists {
						select {
						case sender.send <- outboundFrame{opCode: 0x1, payload: sysBytes}:
						default:
						}
					}
				} else {
					// Route private DM directly to target user
					select {
					case target.send <- outboundFrame{opCode: 0x1, payload: outBytes}:
						log.Printf("Routed DM from '%s' to '%s' (%d bytes)", message.From, message.To, len(outBytes))
					default:
						delete(h.clients, message.To)
						close(target.send)
						log.Printf("[%s | user=%s] Evicting slow client: outbound send buffer full", target.conn.RemoteAddr(), message.To)
					}
				}
			} else {
				// Group broadcast to all connected clients
				log.Printf("Broadcasting message from '%s' (%d bytes) to %d clients", message.From, len(outBytes), len(h.clients))
				for userId, client := range h.clients {
					select {
					case client.send <- outboundFrame{opCode: 0x1, payload: outBytes}:
					default:
						delete(h.clients, userId)
						close(client.send)
						log.Printf("[%s | user=%s] Evicting slow client: outbound send buffer full (active clients: %d)", client.conn.RemoteAddr(), userId, len(h.clients))
					}
				}
			}
		}
	}
}

Updating main.go & Verification:

Finally, extract userId from the request URL inside handleUpgradeRequest and initialize send with our new outboundFrame channel:

func handleUpgradeRequest(hub *Hub, w http.ResponseWriter, r *http.Request) {
	// ... (Existing method and header validation) ...

	userId := r.URL.Query().Get("userId")
	if userId == "" {
		http.Error(w, "Missing userId query parameter", http.StatusBadRequest)
		return
	}

	// ... (Existing SHA-1 proof, Hijack, and 101 Flush) ...

	client := &Client{
		conn:   conn,
		bufrw:  bufrw,
		send:   make(chan outboundFrame, 256),
		hub:    hub,
		userId: userId,
	}
	hub.register <- client

	go client.writeLoop()
	client.readLoop()
}


Check-Point: Testing Group Broadcasts, 1-on-1 DMs & Offline Handling

Restart your server (go run .) and open two browser tabs (Tab A for alice and Tab B for bob):

  1. In Tab A (Alice):

    let ws = new WebSocket("ws://localhost:3333/ws?userId=alice");
    ws.onmessage = (e) => console.log("Alice received:", JSON.parse(e.data));
    
  2. In Tab B (Bob):

    let ws = new WebSocket("ws://localhost:3333/ws?userId=bob");
    ws.onmessage = (e) => console.log("Bob received:", JSON.parse(e.data));
    
  3. Run all three messaging scenarios from Alice's console

    // 1. Private 1-on-1 DM (Only Bob's console logs this!)
    ws.send(JSON.stringify({ to: "bob", text: "Hey Bob, secret message!" }));
    
    // 2. Public Group Broadcast (Both Alice and Bob receive this)
    ws.send(JSON.stringify({ text: "Hello everyone in the room!" }));
    
    // 3. Offline User Handling (Alice immediately gets a System notice back)
    ws.send(JSON.stringify({ to: "charlie", text: "Are you online?" }));
    

You'll see Bob receive the private DM exclusively, both tabs receive the group broadcast, and Alice receive {"from": "System", "text": "User 'charlie' is offline"} proving your routed WebSocket engine works end-to-end!


Summary

In this blog, we’ve delved into the world of WebSockets and explored building our own real-time, full-duplex communication engine from scratch using Go. We started by understanding the limitations of repetitive HTTP polling and how WebSockets upgrade a single HTTP request into a persistent, bidirectional TCP tunnel. Using a walkie-talkie versus an open phone call analogy, we made these concepts more relatable by comparing half-duplex turn-taking to a full-duplex live line where both caller and receiver can speak simultaneously.

We then moved on to a practical, step-by-step implementation across 5 incremental milestones using nothing but Go's powerful standard library. Along the way, we explored the critical architectural and wire-protocol decisions required to keep our engine fast, safe, and race-free, including HTTP connection hijacking, decoding Big-Endian variable-length headers, XOR payload unmasking, isolating socket writes into a dedicated goroutine, and orchestrating multi-client broadcasts and 1-on-1 DMs through a single-owner channel loop.


Over to You !

If you made it this far, thank you for reading! I'd love to hear your thoughts, drop a comment below with your suggestions, or any bottlenecks you ran into while testing the loop.

If you found this guide helpful, please consider sharing or reposting it to help other developers!

For more hands-on backend deep-dives and system architecture projects, let's connect across the web:

Until next time, keep cooking up clean code! 🚀

About the author

  • Hi, I'm Uttkarsh , a tech enthusiast with a knack for building cool stuff. I enjoy translating ideas into code, whether it's crafting user interfaces or tackling new challenges. There's a certain satisfaction in creating things. I'm here to keep learning, coding, and having fun along the way. When not coding, you'll find me exploring different interests and trying to make the most out of every moment. Open to collaborations and always up for a tech chat. Feel free to connect!

No comments yet. Be the first to comment.