WebSockets

suggest change

HTTP is request/response: the client asks, the server answers, and the server can't send anything on its own. WebSocket (RFC 6455) removes that limit. The client opens a normal HTTP request with an Upgrade: websocket header. If the server agrees, it answers 101 Switching Protocols, and from then on the same TCP connection carries messages in both directions, at any time.

WebSockets are used for chat, live dashboards, notifications, multiplayer games, collaborative editors and anything else where the server pushes data to the browser.

What you get on top of a raw TCP socket:

The Go standard library doesn't implement WebSockets. (golang.org/x/net/websocket exists, but its own docs point you to other packages.) The two widely used libraries are:

go get github.com/coder/websocket@latest

The examples use github.com/coder/websocket v1.8.15, github.com/gorilla/websocket v1.5.3 and Go 1.27.

To keep the examples self-contained, most of them start the server with httptest.NewServer and connect to it with a Go client in the same program. In a real program the handler is registered on your HTTP server like any other handler.

Echo server and client

The server side is a regular http.Handler. websocket.Accept performs the handshake and returns a *websocket.Conn. The client side calls websocket.Dial with a ws:// or wss:// URL.

package main

import (
	"context"
	"errors"
	"fmt"
	"log"
	"net/http"
	"net/http/httptest"
	"strings"
	"time"

	"github.com/coder/websocket"
)

// echoHandler upgrades the request to a WebSocket and sends every
// message back to the client.
func echoHandler(w http.ResponseWriter, r *http.Request) {
	c, err := websocket.Accept(w, r, nil)
	if err != nil {
		// Accept has already written an HTTP error response
		log.Println("accept:", err)
		return
	}
	defer c.CloseNow()

	ctx := r.Context()
	for {
		typ, data, err := c.Read(ctx)
		if err != nil {
			if websocket.CloseStatus(err) == websocket.StatusNormalClosure {
				fmt.Println("server: client said goodbye")
			} else if !errors.Is(err, context.Canceled) {
				log.Println("server: read:", err)
			}
			return
		}
		fmt.Printf("server: got %v, %d bytes\n", typ, len(data))
		if err := c.Write(ctx, typ, data); err != nil {
			log.Println("server: write:", err)
			return
		}
	}
}

func main() {
	srv := httptest.NewServer(http.HandlerFunc(echoHandler))
	defer srv.Close()

	// http://127.0.0.1:port => ws://127.0.0.1:port
	url := "ws" + strings.TrimPrefix(srv.URL, "http")

	ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
	defer cancel()

	c, resp, err := websocket.Dial(ctx, url, nil)
	if err != nil {
		log.Fatal(err)
	}
	defer c.CloseNow()
	fmt.Println("client: handshake status", resp.StatusCode)

	for _, msg := range []string{"hello", "world"} {
		if err := c.Write(ctx, websocket.MessageText, []byte(msg)); err != nil {
			log.Fatal(err)
		}
		typ, data, err := c.Read(ctx)
		if err != nil {
			log.Fatal(err)
		}
		fmt.Printf("client: got %v %q\n", typ, data)
	}

	c.Write(ctx, websocket.MessageBinary, []byte{0xde, 0xad, 0xbe, 0xef})
	_, data, _ := c.Read(ctx)
	fmt.Printf("client: got % x\n", data)

	// Close sends a close frame and waits for the server's reply.
	if err := c.Close(websocket.StatusNormalClosure, "bye"); err != nil {
		log.Fatal(err)
	}
	time.Sleep(50 * time.Millisecond) // let the server print
}
client: handshake status 101
server: got MessageText, 5 bytes
client: got MessageText "hello"
server: got MessageText, 5 bytes
client: got MessageText "world"
server: got MessageBinary, 4 bytes
client: got de ad be ef
server: client said goodbye

Things to know:

JSON messages

Most applications send JSON. The wsjson subpackage reads a text message and unmarshals it, or marshals a value and sends it:

package main

import (
	"context"
	"fmt"
	"log"
	"net/http"
	"net/http/httptest"
	"strings"
	"time"

	"github.com/coder/websocket"
	"github.com/coder/websocket/wsjson"
)

type Request struct {
	ID int    `json:"id"`
	Op string `json:"op"`
	A  int    `json:"a"`
	B  int    `json:"b"`
}

type Response struct {
	ID     int    `json:"id"`
	Result int    `json:"result,omitempty"`
	Error  string `json:"error,omitempty"`
}

func calcHandler(w http.ResponseWriter, r *http.Request) {
	c, err := websocket.Accept(w, r, nil)
	if err != nil {
		return
	}
	defer c.CloseNow()

	for {
		var req Request
		// Read reads one text message and json.Unmarshals it
		if err := wsjson.Read(r.Context(), c, &req); err != nil {
			return
		}
		resp := Response{ID: req.ID}
		switch req.Op {
		case "add":
			resp.Result = req.A + req.B
		case "mul":
			resp.Result = req.A * req.B
		default:
			resp.Error = "unknown op: " + req.Op
		}
		// Write json.Marshals v and sends it as a text message
		if err := wsjson.Write(r.Context(), c, resp); err != nil {
			return
		}
	}
}

func main() {
	srv := httptest.NewServer(http.HandlerFunc(calcHandler))
	defer srv.Close()

	ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
	defer cancel()

	c, _, err := websocket.Dial(ctx, "ws"+strings.TrimPrefix(srv.URL, "http"), nil)
	if err != nil {
		log.Fatal(err)
	}
	defer c.Close(websocket.StatusNormalClosure, "")

	reqs := []Request{
		{ID: 1, Op: "add", A: 2, B: 3},
		{ID: 2, Op: "mul", A: 6, B: 7},
		{ID: 3, Op: "div", A: 1, B: 0},
	}
	for _, req := range reqs {
		if err := wsjson.Write(ctx, c, req); err != nil {
			log.Fatal(err)
		}
		var resp Response
		if err := wsjson.Read(ctx, c, &resp); err != nil {
			log.Fatal(err)
		}
		fmt.Printf("%+v\n", resp)
	}
}
{ID:1 Result:5 Error:}
{ID:2 Result:42 Error:}
{ID:3 Result:0 Error:unknown op: div}

Each wsjson.Write sends exactly one message and each wsjson.Read reads exactly one. Add a type or op field to your messages, like Op above, so the receiver knows how to decode and route them. Including an ID lets the client match a response to a request when several are in flight. See JSON for more about struct tags.

For other formats (protobuf, msgpack, gob) send binary messages with c.Write(ctx, websocket.MessageBinary, data). For large messages you can use c.Writer and c.Reader, which return an io.WriteCloser and an io.Reader so you can stream a message without having it all in memory.

Close codes, read limits and errors

A close frame carries a numeric status code and a short reason (at most 125 bytes). The library defines constants for the codes from the RFC, like StatusNormalClosure (1000), StatusGoingAway (1001), StatusPolicyViolation (1008), StatusMessageTooBig (1009) and StatusInternalError (1011). Applications can use their own codes in the 4000-4999 range.

package main

import (
	"context"
	"errors"
	"fmt"
	"io"
	"log"
	"net/http"
	"net/http/httptest"
	"strings"
	"time"

	"github.com/coder/websocket"
)

func handler(w http.ResponseWriter, r *http.Request) {
	c, err := websocket.Accept(w, r, nil)
	if err != nil {
		return
	}
	defer c.CloseNow()

	// The default limit is 32 KiB. Reading a bigger message closes the
	// connection with StatusMessageTooBig.
	c.SetReadLimit(16)

	for {
		_, data, err := c.Read(r.Context())
		if err != nil {
			fmt.Println("server: read error:", err)
			return
		}
		if string(data) == "quit" {
			c.Close(websocket.StatusPolicyViolation, "quit is not allowed")
			return
		}
	}
}

func dial(ctx context.Context, url string) *websocket.Conn {
	c, _, err := websocket.Dial(ctx, url, nil)
	if err != nil {
		log.Fatal(err)
	}
	return c
}

func main() {
	mux := http.NewServeMux()
	mux.HandleFunc("/ws", handler)
	srv := httptest.NewServer(mux)
	defer srv.Close()
	url := "ws" + strings.TrimPrefix(srv.URL, "http") + "/ws"
	ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
	defer cancel()

	// 1. the server closes the connection with a status code
	c := dial(ctx, url)
	c.Write(ctx, websocket.MessageText, []byte("quit"))
	_, _, err := c.Read(ctx)
	fmt.Println("client: status:", websocket.CloseStatus(err))
	var ce websocket.CloseError
	if errors.As(err, &ce) {
		fmt.Printf("client: code=%d reason=%q\n", ce.Code, ce.Reason)
	}

	// 2. message larger than the server's read limit
	c = dial(ctx, url)
	c.Write(ctx, websocket.MessageText, []byte(strings.Repeat("x", 100)))
	_, _, err = c.Read(ctx)
	fmt.Println("client: status:", websocket.CloseStatus(err))

	// 3. a regular HTTP request to a WebSocket endpoint
	resp, err := http.Get(srv.URL + "/ws")
	if err != nil {
		log.Fatal(err)
	}
	body, _ := io.ReadAll(resp.Body)
	resp.Body.Close()
	fmt.Printf("http: %s %q\n", resp.Status, body)

	// 4. dialing a URL that isn't a WebSocket endpoint
	_, resp, err = websocket.Dial(ctx, "ws"+strings.TrimPrefix(srv.URL, "http")+"/nope", nil)
	fmt.Println("dial error:", err)
	fmt.Println("response status:", resp.StatusCode)

	// CloseStatus returns -1 for errors that are not close frames
	fmt.Println(websocket.CloseStatus(io.EOF))
	time.Sleep(50 * time.Millisecond)
}
client: status: StatusPolicyViolation
client: code=1008 reason="quit is not allowed"
server: read error: failed to read: websocket: message too big: read limited at 17 bytes
client: status: StatusMessageTooBig
http: 426 Upgrade Required "WebSocket protocol violation: Connection header \"\" does not contain Upgrade\n"
dial error: failed to WebSocket dial: expected handshake response status code 101 but got 404
response status: 404
StatusCode(-1)

What happened:

  1. The server closed with StatusPolicyViolation. The client's Read returned a websocket.CloseError. websocket.CloseStatus(err) extracts the code. Use errors.As to get the reason as well.
  2. By default a connection refuses messages bigger than 32 KiB. This protects the server from clients that send huge messages to use up memory. SetReadLimit changes the limit. When a message is too big the connection is closed with StatusMessageTooBig. Set the limit to the largest message your protocol needs, not higher.
  3. A plain HTTP request to the WebSocket endpoint gets 426 Upgrade Required. Accept wrote that response.
  4. If the server doesn't accept the upgrade, Dial returns an error together with the HTTP response, so you can look at the status code or the body (for example a 401 from your authentication code).

CloseStatus returns -1 when the error isn't a close frame, for example when the network connection drops without a close handshake. Treat that as an abnormal disconnect.

Origin checks, authentication and subprotocols

Browsers send cookies with WebSocket handshakes, and the same-origin policy doesn't apply to WebSockets. Without a check, any web page a logged-in user visits could open a WebSocket to your server with the user's cookies (cross-site WebSocket hijacking). That's why Accept rejects requests whose Origin header doesn't match the server's host. Use OriginPatterns to allow other origins:

package main

import (
	"context"
	"fmt"
	"net/http"
	"net/http/httptest"
	"strings"

	"github.com/coder/websocket"
)

func wsHandler(w http.ResponseWriter, r *http.Request) {
	// Authenticate before upgrading, while you can still send
	// a normal HTTP error response.
	if r.URL.Query().Get("token") != "secret" {
		http.Error(w, "unauthorized", http.StatusUnauthorized)
		return
	}
	c, err := websocket.Accept(w, r, &websocket.AcceptOptions{
		// pages served from these hosts may connect, in addition
		// to pages served by this server
		OriginPatterns: []string{"app.example.com", "*.example.org"},
		Subprotocols:   []string{"chat.v2", "chat.v1"},
	})
	if err != nil {
		return
	}
	defer c.CloseNow()
	c.Write(r.Context(), websocket.MessageText, []byte("welcome, protocol="+c.Subprotocol()))
	c.Close(websocket.StatusNormalClosure, "")
}

func try(url, origin string, protocols ...string) {
	opts := &websocket.DialOptions{
		HTTPHeader:   http.Header{},
		Subprotocols: protocols,
	}
	if origin != "" {
		opts.HTTPHeader.Set("Origin", origin)
	}
	label := origin
	if label == "" {
		label = "(no Origin)"
	} else if !strings.Contains(origin, "example") {
		label = "(same origin)"
	}
	ctx := context.Background()
	c, resp, err := websocket.Dial(ctx, url, opts)
	if err != nil {
		fmt.Printf("%-26s rejected: HTTP %d\n", label, resp.StatusCode)
		return
	}
	defer c.CloseNow()
	_, data, _ := c.Read(ctx)
	fmt.Printf("%-26s %s\n", label, data)
}

func main() {
	srv := httptest.NewServer(http.HandlerFunc(wsHandler))
	defer srv.Close()
	base := "ws" + strings.TrimPrefix(srv.URL, "http")

	try(base, "")                      // no token
	try(base+"?token=secret", "")      // non-browser client: no Origin
	try(base+"?token=secret", srv.URL) // same origin
	try(base+"?token=secret", "https://app.example.com", "chat.v1")
	try(base+"?token=secret", "https://eu.example.org", "chat.v1", "chat.v2")
	try(base+"?token=secret", "https://evil.example.net")
}
(no Origin)                rejected: HTTP 401
(no Origin)                welcome, protocol=
(same origin)              welcome, protocol=
https://app.example.com    welcome, protocol=chat.v1
https://eu.example.org     welcome, protocol=chat.v2
https://evil.example.net   rejected: HTTP 403

Notes:

Server push, CloseRead and ping

Some connections only send data from the server to the client: a stock ticker, a progress bar, log tailing. You still have to read from the connection, because control frames (ping, pong, close) are processed only while reading. c.CloseRead starts a goroutine that does this for you. It returns a context that is cancelled when the connection closes.

To detect peers that disappeared without closing the connection (laptop lid closed, network gone), send pings. c.Ping sends a ping and waits for the pong:

package main

import (
	"context"
	"fmt"
	"log"
	"net/http"
	"net/http/httptest"
	"strings"
	"time"

	"github.com/coder/websocket"
)

// ticks pushes the current count to the client every 100ms.
// The client is not expected to send anything.
func ticks(w http.ResponseWriter, r *http.Request) {
	c, err := websocket.Accept(w, r, nil)
	if err != nil {
		return
	}
	defer c.CloseNow()

	// CloseRead reads (and answers) control frames in the background.
	// The returned context is cancelled when the connection is closed.
	ctx := c.CloseRead(r.Context())

	ticker := time.NewTicker(100 * time.Millisecond)
	defer ticker.Stop()
	heartbeat := time.NewTicker(220 * time.Millisecond)
	defer heartbeat.Stop()

	for n := 1; ; {
		select {
		case <-ctx.Done():
			fmt.Println("server: client is gone")
			return
		case <-ticker.C:
			msg := fmt.Sprintf("tick %d", n)
			n++
			if err := c.Write(ctx, websocket.MessageText, []byte(msg)); err != nil {
				return
			}
		case <-heartbeat.C:
			// Ping waits for the pong. No pong in time means a dead peer.
			pctx, cancel := context.WithTimeout(ctx, 2*time.Second)
			err := c.Ping(pctx)
			cancel()
			if err != nil {
				fmt.Println("server: ping failed:", err)
				return
			}
			fmt.Println("server: pong received")
		}
	}
}

func main() {
	srv := httptest.NewServer(http.HandlerFunc(ticks))
	defer srv.Close()

	ctx := context.Background()
	c, _, err := websocket.Dial(ctx, "ws"+strings.TrimPrefix(srv.URL, "http"), nil)
	if err != nil {
		log.Fatal(err)
	}
	// The client answers pings automatically, but only while it is reading.
	for range 5 {
		_, data, err := c.Read(ctx)
		if err != nil {
			log.Fatal(err)
		}
		fmt.Println("client:", string(data))
	}
	c.Close(websocket.StatusNormalClosure, "")
	time.Sleep(50 * time.Millisecond)
}
client: tick 1
client: tick 2
server: pong received
client: tick 3
client: tick 4
server: pong received
client: tick 5
server: client is gone

Both sides answer pings automatically, but only while something is reading from the connection. That's why Ping needs either a goroutine calling Read or CloseRead. If nothing reads, Ping waits until its context expires.

The library doesn't send pings by itself. TCP keep-alive (enabled by default in Go) detects dead peers eventually, but it can take minutes. Proxies and load balancers often close idle connections after 60 seconds, so sending a ping every 20-30 seconds keeps the connection alive and finds dead clients quickly.

Broadcasting: a chat hub

A chat server receives a message from one client and sends it to all others. The usual design:

package main

import (
	"context"
	"fmt"
	"log"
	"net/http"
	"net/http/httptest"
	"strings"
	"sync"
	"time"

	"github.com/coder/websocket"
)

// client is one connected WebSocket. Messages for it are queued in send.
type client struct {
	name string
	send chan []byte
}

// Hub keeps track of connected clients and broadcasts messages to them.
type Hub struct {
	mu      sync.Mutex
	clients map[*client]struct{}
}

func NewHub() *Hub {
	return &Hub{clients: make(map[*client]struct{})}
}

func (h *Hub) add(c *client) {
	h.mu.Lock()
	h.clients[c] = struct{}{}
	h.mu.Unlock()
}

func (h *Hub) remove(c *client) {
	h.mu.Lock()
	delete(h.clients, c)
	h.mu.Unlock()
}

// Broadcast never blocks: a client whose queue is full is too slow
// and is dropped instead of slowing down everybody else.
func (h *Hub) Broadcast(msg []byte) {
	h.mu.Lock()
	defer h.mu.Unlock()
	for c := range h.clients {
		select {
		case c.send <- msg:
		default:
			delete(h.clients, c)
			close(c.send)
		}
	}
}

func (h *Hub) ServeHTTP(w http.ResponseWriter, r *http.Request) {
	conn, err := websocket.Accept(w, r, nil)
	if err != nil {
		return
	}
	defer conn.CloseNow()

	cl := &client{name: r.URL.Query().Get("name"), send: make(chan []byte, 16)}
	h.add(cl)
	defer h.remove(cl)
	h.Broadcast([]byte(cl.name + " joined"))

	ctx, cancel := context.WithCancel(r.Context())
	defer cancel()

	// reader goroutine: messages from this client go to everybody
	go func() {
		defer cancel()
		for {
			_, data, err := conn.Read(ctx)
			if err != nil {
				return
			}
			h.Broadcast([]byte(cl.name + ": " + string(data)))
		}
	}()

	// writer loop: send queued messages to this client
	for {
		select {
		case msg, ok := <-cl.send:
			if !ok {
				conn.Close(websocket.StatusPolicyViolation, "too slow")
				return
			}
			wctx, wcancel := context.WithTimeout(ctx, 5*time.Second)
			err := conn.Write(wctx, websocket.MessageText, msg)
			wcancel()
			if err != nil {
				return
			}
		case <-ctx.Done():
			return
		}
	}
}

func main() {
	srv := httptest.NewServer(NewHub())
	defer srv.Close()
	base := "ws" + strings.TrimPrefix(srv.URL, "http")
	ctx := context.Background()

	var conns []*websocket.Conn
	for _, name := range []string{"alice", "bob"} {
		c, _, err := websocket.Dial(ctx, base+"?name="+name, nil)
		if err != nil {
			log.Fatal(err)
		}
		conns = append(conns, c)
		time.Sleep(20 * time.Millisecond) // keep the join order stable
	}
	alice, bob := conns[0], conns[1]

	alice.Write(ctx, websocket.MessageText, []byte("hi bob"))
	time.Sleep(20 * time.Millisecond)
	bob.Write(ctx, websocket.MessageText, []byte("hello alice"))

	readN := func(who string, c *websocket.Conn, n int) {
		for range n {
			_, data, err := c.Read(ctx)
			if err != nil {
				log.Fatal(err)
			}
			fmt.Printf("%-5s <- %s\n", who, data)
		}
	}
	readN("alice", alice, 4) // alice joined, bob joined, 2 messages
	readN("bob", bob, 3)     // bob joined, 2 messages

	alice.Close(websocket.StatusNormalClosure, "")
	bob.Close(websocket.StatusNormalClosure, "")
}
alice <- alice joined
alice <- bob joined
alice <- alice: hi bob
alice <- bob: hello alice
bob   <- bob joined
bob   <- alice: hi bob
bob   <- bob: hello alice

The important decision is what to do with slow clients. A client on a bad mobile connection can't keep up, and Write to it blocks. If Broadcast wrote to each connection directly, one slow client would block the whole chat. Here every client has a queue of 16 messages, Broadcast never blocks, and a client whose queue is full is disconnected. A client can reconnect and reload the history.

*websocket.Conn from coder/websocket allows concurrent Write calls from many goroutines, so in a simpler program the broadcaster could write directly. Only one goroutine may call Read (or Reader) at a time.

This hub works within one process. To broadcast across several server instances, publish messages to a shared bus such as Redis pub/sub and have each instance forward them to its own clients.

A complete server with a browser client

Here is a standalone program: it serves an HTML page with JavaScript that connects to /ws, and the server replies to each message in upper case. It also shuts down gracefully on Ctrl+C.

package main

import (
	"context"
	"errors"
	"log"
	"net"
	"net/http"
	"os"
	"os/signal"
	"strings"
	"sync"
	"time"

	"github.com/coder/websocket"
)

const indexHTML = `<!doctype html>
<title>WebSocket echo</title>
<input id="msg" placeholder="type and press Enter" autofocus>
<pre id="log"></pre>
<script>
const log = (s) => document.getElementById("log").textContent += s + "\n";
const proto = location.protocol === "https:" ? "wss:" : "ws:";
const ws = new WebSocket(proto + "//" + location.host + "/ws");
ws.onopen = () => log("connected");
ws.onmessage = (e) => log("< " + e.data);
ws.onclose = (e) => log("closed: " + e.code + " " + e.reason);
document.getElementById("msg").onkeydown = (e) => {
  if (e.key === "Enter" && ws.readyState === WebSocket.OPEN) {
    ws.send(e.target.value);
    log("> " + e.target.value);
    e.target.value = "";
  }
};
</script>`

// handlers is used to wait for WebSocket handlers during shutdown
var handlers sync.WaitGroup

func handleWS(w http.ResponseWriter, r *http.Request) {
	c, err := websocket.Accept(w, r, nil)
	if err != nil {
		return
	}
	handlers.Add(1)
	defer handlers.Done()
	defer c.CloseNow()

	// r.Context() is cancelled when the server shuts down (see BaseContext).
	// Cancelling the context of a Read closes the connection abruptly,
	// so instead we do a proper close handshake when that happens.
	stop := context.AfterFunc(r.Context(), func() {
		c.Close(websocket.StatusGoingAway, "server is shutting down")
	})
	defer stop()

	ctx := context.WithoutCancel(r.Context())
	for {
		typ, data, err := c.Read(ctx)
		if err != nil {
			return
		}
		reply := strings.ToUpper(string(data))
		if err := c.Write(ctx, typ, []byte(reply)); err != nil {
			return
		}
	}
}

func main() {
	mux := http.NewServeMux()
	mux.HandleFunc("GET /{$}", func(w http.ResponseWriter, r *http.Request) {
		w.Header().Set("Content-Type", "text/html; charset=utf-8")
		w.Write([]byte(indexHTML))
	})
	mux.HandleFunc("GET /ws", handleWS)

	// Shutdown doesn't touch hijacked connections, so WebSocket handlers
	// get a context that we cancel ourselves when shutting down.
	baseCtx, cancelBase := context.WithCancel(context.Background())
	srv := &http.Server{
		Addr:        "localhost:8080",
		Handler:     mux,
		BaseContext: func(net.Listener) context.Context { return baseCtx },
	}

	go func() {
		log.Println("listening on http://" + srv.Addr)
		if err := srv.ListenAndServe(); !errors.Is(err, http.ErrServerClosed) {
			log.Fatal(err)
		}
	}()

	sigCtx, stop := signal.NotifyContext(context.Background(), os.Interrupt)
	defer stop()
	<-sigCtx.Done()
	log.Println("shutting down")

	ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
	defer cancel()
	srv.Shutdown(ctx) // stop accepting, finish regular HTTP requests
	cancelBase()      // tell WebSocket handlers to close
	handlers.Wait()
	log.Println("done")
}

Run it with go run . and open http://localhost:8080 in a few browser tabs. When you press Ctrl+C, every page prints closed: 1001 server is shutting down.

Shutting down needs extra care:

See OS Signals for more about handling Ctrl+C.

In production, the server usually runs behind TLS, and browsers connect with wss://. If a reverse proxy sits in front of it, the proxy must forward the Upgrade and Connection headers (nginx needs proxy_http_version 1.1 and explicit proxy_set_header lines) and its read timeout must be longer than your ping interval.

TLS and testing

httptest.NewTLSServer starts a test server with a self-signed certificate. Pass its client to Dial so the certificate is trusted:

package main

import (
	"context"
	"fmt"
	"log"
	"net/http"
	"net/http/httptest"
	"strings"

	"github.com/coder/websocket"
)

func main() {
	srv := httptest.NewTLSServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		c, err := websocket.Accept(w, r, nil)
		if err != nil {
			return
		}
		defer c.CloseNow()
		c.Write(r.Context(), websocket.MessageText, []byte("hello over TLS"))
		c.Close(websocket.StatusNormalClosure, "")
	}))
	defer srv.Close()

	url := "wss" + strings.TrimPrefix(srv.URL, "https")
	ctx := context.Background()
	// srv.Client() trusts the test server's self-signed certificate
	c, _, err := websocket.Dial(ctx, url, &websocket.DialOptions{HTTPClient: srv.Client()})
	if err != nil {
		log.Fatal(err)
	}
	defer c.CloseNow()
	_, data, err := c.Read(ctx)
	fmt.Println(string(data), err)
}
hello over TLS <nil>

This is also the way to write tests for WebSocket handlers: start the handler with httptest.NewServer (or NewTLSServer), dial it, exchange messages and check the results, exactly like the examples in this article. See Testing HTTP requests for more about httptest.

gorilla/websocket

github.com/gorilla/websocket predates context and has a different API: an Upgrader instead of Accept, ReadMessage and WriteMessage instead of Read and Write, and deadlines instead of contexts.

go get github.com/gorilla/websocket@latest
package main

import (
	"fmt"
	"log"
	"net/http"
	"net/http/httptest"
	"strings"
	"time"

	"github.com/gorilla/websocket"
)

const (
	writeWait  = 10 * time.Second
	pongWait   = 60 * time.Second
	pingPeriod = pongWait * 9 / 10 // must be less than pongWait
)

var upgrader = websocket.Upgrader{
	ReadBufferSize:  1024,
	WriteBufferSize: 1024,
	// The default CheckOrigin rejects cross-origin requests.
	// Replace it to allow other origins.
}

func echo(w http.ResponseWriter, r *http.Request) {
	conn, err := upgrader.Upgrade(w, r, nil)
	if err != nil {
		return // Upgrade has written an HTTP error response
	}
	defer conn.Close()

	conn.SetReadLimit(4096)
	// A read times out unless a pong (or any message) arrives in time.
	conn.SetReadDeadline(time.Now().Add(pongWait))
	conn.SetPongHandler(func(string) error {
		return conn.SetReadDeadline(time.Now().Add(pongWait))
	})

	// gorilla allows one concurrent writer: everything that writes,
	// including pings, happens in this goroutine.
	out := make(chan []byte, 8)
	go func() {
		ticker := time.NewTicker(pingPeriod)
		defer ticker.Stop()
		for {
			select {
			case msg, ok := <-out:
				conn.SetWriteDeadline(time.Now().Add(writeWait))
				if !ok {
					conn.WriteMessage(websocket.CloseMessage,
						websocket.FormatCloseMessage(websocket.CloseNormalClosure, ""))
					return
				}
				if err := conn.WriteMessage(websocket.TextMessage, msg); err != nil {
					return
				}
			case <-ticker.C:
				conn.SetWriteDeadline(time.Now().Add(writeWait))
				if err := conn.WriteMessage(websocket.PingMessage, nil); err != nil {
					return
				}
			}
		}
	}()

	defer close(out)
	for {
		_, msg, err := conn.ReadMessage()
		if err != nil {
			if websocket.IsCloseError(err, websocket.CloseNormalClosure) {
				fmt.Println("server: normal close")
			} else {
				fmt.Println("server:", err)
			}
			return
		}
		out <- []byte(strings.ToUpper(string(msg)))
	}
}

func main() {
	srv := httptest.NewServer(http.HandlerFunc(echo))
	defer srv.Close()

	url := "ws" + strings.TrimPrefix(srv.URL, "http")
	conn, resp, err := websocket.DefaultDialer.Dial(url, nil)
	if err != nil {
		log.Fatal(err)
	}
	fmt.Println("status:", resp.Status)

	for _, s := range []string{"gorilla", "websocket"} {
		conn.WriteMessage(websocket.TextMessage, []byte(s))
		typ, msg, err := conn.ReadMessage()
		if err != nil {
			log.Fatal(err)
		}
		fmt.Println(typ == websocket.TextMessage, string(msg))
	}

	// polite close: send a close frame, then close the TCP connection
	conn.WriteMessage(websocket.CloseMessage,
		websocket.FormatCloseMessage(websocket.CloseNormalClosure, "bye"))
	conn.Close()
	time.Sleep(50 * time.Millisecond)
}
status: 101 Switching Protocols
true GORILLA
true WEBSOCKET
server: normal close

Rules you must follow with gorilla:

Choose coder/websocket for new code if you like contexts and concurrent writes. Choose gorilla/websocket if your codebase or a library you use already depends on it. Both are stable and fully implement the protocol, including compression (permessage-deflate), which is off by default in coder/websocket and in gorilla's Upgrader.

Summary

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents