Push live order updates to browsers from a Go backend with coder/websocket or gorilla/websocket, including origin checks, cookie auth, pings, slow-client handling and fan-out across more than one instance.

Go makes the HTTP side of a WebSocket server easy, but the standard library stops there: there is no WebSocket package in net/http, and the golang.org/x/net/websocket docs themselves point to more actively maintained packages, so the first decision is a library, and the next ones are about what happens around each connection.
A socket that works in a demo still has to check the Origin, authenticate the upgrade request, ping clients that go quiet behind a proxy, and drop a client that cannot keep up before its buffer blocks everyone else. Once the API runs on two instances, a message published on one of them also has to reach browsers connected to the other.
This guide builds a live order feed for a store dashboard: a browser opens /live, and every status change for that store is pushed to it. It starts with Encore, then shows the same server with net/http and gorilla/websocket, and ends with fan-out across instances.
Encore is a backend framework with built-in infrastructure, and a WebSocket in Go is a raw endpoint: an ordinary http.HandlerFunc that still goes through Encore's auth handler, so the upgrade request is authenticated before your code runs. TypeScript services use streaming APIs for the same job. The socket itself comes from coder/websocket, which takes a context.Context on every read and write.

Run in your terminal to get started locally.
Browsers cannot set an Authorization header on a WebSocket, but they do send cookies with the handshake. The auth handler reads the session cookie through a cookie:"session" field, checks an HMAC signature and an expiry, and returns the store the user belongs to. The signing key is an Encore secret, so it never sits in the repository:
// live/auth.go
package live
import (
"context"
"crypto/hmac"
"crypto/sha256"
"crypto/subtle"
"encoding/hex"
"net/http"
"strconv"
"strings"
"time"
"encore.dev/beta/auth"
"encore.dev/beta/errs"
)
var secrets struct {
// SessionHMACKey signs the "session" cookie issued at login.
SessionHMACKey string
}
type AuthParams struct {
Session *http.Cookie `cookie:"session"`
}
type AuthData struct {
StoreID string
}
// AuthHandler accepts a cookie of the form "<user>.<store>.<unix-expiry>.<hex hmac>".
//
//encore:authhandler
func AuthHandler(ctx context.Context, p *AuthParams) (auth.UID, *AuthData, error) {
unauth := &errs.Error{Code: errs.Unauthenticated, Message: "invalid session"}
if p.Session == nil || secrets.SessionHMACKey == "" {
return "", nil, unauth
}
parts := strings.Split(p.Session.Value, ".")
if len(parts) != 4 {
return "", nil, unauth
}
exp, err := strconv.ParseInt(parts[2], 10, 64)
if err != nil || exp < time.Now().Unix() {
return "", nil, unauth
}
mac := hmac.New(sha256.New, []byte(secrets.SessionHMACKey))
mac.Write([]byte(strings.Join(parts[:3], ".")))
want := hex.EncodeToString(mac.Sum(nil))
if subtle.ConstantTimeCompare([]byte(parts[3]), []byte(want)) != 1 {
return "", nil, unauth
}
return auth.UID(parts[0]), &AuthData{StoreID: parts[1]}, nil
}
The hub keeps the open connections on this instance, grouped by store, and each connection gets a buffered channel. A client whose buffer is full is dropped instead of blocking the broadcast for everyone else. OriginPatterns limits which sites can open the socket with the user's cookie, and CloseRead reads in the background so pings get their pongs and the context ends when the browser goes away:
// live/live.go
package live
import (
"context"
"encoding/json"
"net/http"
"sync"
"time"
"encore.dev/beta/auth"
"encore.dev/beta/errs"
"github.com/coder/websocket"
)
type Update struct {
OrderID string `json:"order_id"`
Status string `json:"status"`
}
type client struct {
send chan []byte
}
// hub holds the open connections on this instance, grouped by store.
type hub struct {
mu sync.Mutex
conns map[string]map[*client]struct{}
}
var stores = &hub{conns: map[string]map[*client]struct{}{}}
func (h *hub) add(store string, c *client) {
h.mu.Lock()
defer h.mu.Unlock()
if h.conns[store] == nil {
h.conns[store] = map[*client]struct{}{}
}
h.conns[store][c] = struct{}{}
}
// remove closes the client's send channel once, whoever gets there first.
func (h *hub) remove(store string, c *client) {
h.mu.Lock()
defer h.mu.Unlock()
if _, ok := h.conns[store][c]; ok {
delete(h.conns[store], c)
close(c.send)
}
}
func (h *hub) broadcast(store string, msg []byte) {
h.mu.Lock()
defer h.mu.Unlock()
for c := range h.conns[store] {
select {
case c.send <- msg:
default:
// The client is not keeping up: drop it instead of blocking the others.
delete(h.conns[store], c)
close(c.send)
}
}
}
// Live upgrades the request to a WebSocket and streams order updates for the caller's store.
//
//encore:api auth raw method=GET path=/live
func Live(w http.ResponseWriter, req *http.Request) {
data := auth.Data().(*AuthData)
conn, err := websocket.Accept(w, req, &websocket.AcceptOptions{
OriginPatterns: []string{"app.example.com", "localhost:*"},
})
if err != nil {
return // Accept has already written an HTTP error response.
}
defer conn.CloseNow()
c := &client{send: make(chan []byte, 16)}
stores.add(data.StoreID, c)
defer stores.remove(data.StoreID, c)
// The client only listens. CloseRead reads (and answers pings and pongs) in the
// background and cancels ctx when the connection closes.
ctx := conn.CloseRead(req.Context())
ping := time.NewTicker(30 * time.Second)
defer ping.Stop()
for {
select {
case msg, ok := <-c.send:
if !ok {
conn.Close(websocket.StatusPolicyViolation, "client too slow")
return
}
wctx, cancel := context.WithTimeout(ctx, 5*time.Second)
err := conn.Write(wctx, websocket.MessageText, msg)
cancel()
if err != nil {
return
}
case <-ping.C:
pctx, cancel := context.WithTimeout(ctx, 10*time.Second)
err := conn.Ping(pctx)
cancel()
if err != nil {
return
}
case <-ctx.Done():
return
}
}
}
type PublishParams struct {
StoreID string `json:"store_id"`
OrderID string `json:"order_id"`
Status string `json:"status"`
}
// Publish sends an update to every connection for a store on this instance.
// Other services call it after they change an order.
//
//encore:api private method=POST path=/live/publish
func Publish(ctx context.Context, p *PublishParams) error {
if p.StoreID == "" || p.OrderID == "" {
return &errs.Error{Code: errs.InvalidArgument, Message: "store_id and order_id are required"}
}
msg, err := json.Marshal(Update{OrderID: p.OrderID, Status: p.Status})
if err != nil {
return err
}
stores.broadcast(p.StoreID, msg)
return nil
}
Publish is private, so only other services in the app can call it, as a typed function call such as live.Publish(ctx, &live.PublishParams{...}). Set the signing key with encore secret set --type dev,local SessionHMACKey. The production value is not in the repository, so an AI coding agent working in the repo cannot read that value; a local override in .secrets.local.cue is readable if it is present. Start the app with encore run, and a WebSocket client that sends a signed session cookie receives {"order_id":"o-1","status":"ready"} as soon as Publish runs for its store. A request without a valid cookie gets a 401 before the upgrade.
The endpoint, the auth handler and the secret are all declared in Go, so a coding agent that adds a new live feed changes one package and checks it against encore run in the same session. The deploy puts the service on Fargate or EKS on AWS, or Cloud Run or GKE on GCP, in your own account.
Best fit: Go teams who want WebSocket endpoints, authentication and the services that publish updates in one codebase, deployed to their own AWS or GCP account.
gorilla/websocket is the long-standing Go WebSocket package, and its chat example is where the read pump and write pump pattern comes from. A connection supports one concurrent reader and one concurrent writer, so the handler runs a goroutine that only reads (to process pongs and notice disconnects) and writes from the main loop. CheckOrigin replaces the default same-origin check:
// main.go
package main
import (
"log"
"net/http"
"time"
"github.com/gorilla/websocket"
)
var upgrader = websocket.Upgrader{
ReadBufferSize: 1024,
WriteBufferSize: 1024,
CheckOrigin: func(r *http.Request) bool {
return r.Header.Get("Origin") == "https://app.example.com"
},
}
const (
writeWait = 10 * time.Second
pongWait = 60 * time.Second
pingPeriod = 50 * time.Second // must be shorter than pongWait
)
func live(w http.ResponseWriter, r *http.Request) {
storeID, ok := storeFromSession(r) // your session check
if !ok {
http.Error(w, "unauthorized", http.StatusUnauthorized)
return
}
conn, err := upgrader.Upgrade(w, r, nil)
if err != nil {
return // Upgrade has already replied with an HTTP error.
}
defer conn.Close()
c := &client{send: make(chan []byte, 16)}
stores.add(storeID, c)
defer stores.remove(storeID, c)
// The reader goroutine only handles control frames and notices disconnects.
conn.SetReadLimit(512)
conn.SetReadDeadline(time.Now().Add(pongWait))
conn.SetPongHandler(func(string) error {
return conn.SetReadDeadline(time.Now().Add(pongWait))
})
done := make(chan struct{})
go func() {
defer close(done)
for {
if _, _, err := conn.ReadMessage(); err != nil {
return
}
}
}()
ticker := time.NewTicker(pingPeriod)
defer ticker.Stop()
for {
select {
case msg, ok := <-c.send:
conn.SetWriteDeadline(time.Now().Add(writeWait))
if !ok {
conn.WriteMessage(websocket.CloseMessage,
websocket.FormatCloseMessage(websocket.ClosePolicyViolation, "client too slow"))
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
}
case <-done:
return
}
}
}
func main() {
http.HandleFunc("GET /live", live)
log.Fatal(http.ListenAndServe(":8080", nil))
}
The hub type is the same as in the Encore version. What is left to you is the session check, where the signing key lives, how other parts of the backend reach broadcast, and the deployment: on AWS an Application Load Balancer supports WebSockets but closes connections idle longer than its idle timeout, which is 60 seconds by default, so the ping period has to stay below it.
Best fit: services that already run on plain net/http, or teams that need gorilla's API for an existing codebase.
Both versions keep connections in memory, so broadcast only reaches browsers connected to the instance that received the update. As soon as the service scales to two Fargate tasks or two Cloud Run instances, half the dashboards miss half the updates.
The fix is to publish the update somewhere every instance listens, and have each instance broadcast to its own connections. If the service already has Postgres, LISTEN/NOTIFY is enough for small payloads (a NOTIFY payload must be shorter than 8000 bytes in the default configuration, per the Postgres docs). With Encore, Publish runs SELECT pg_notify('store_updates', $1) on a database declared with sqldb.NewDatabase, and a goroutine started from the service's init holds one connection from sqldb.Driver[*pgxpool.Pool](db), runs LISTEN store_updates, and calls stores.broadcast for each notification with conn.Conn().WaitForNotification(ctx). Notifications are not stored, so a dashboard that reconnects should fetch the current order state over a normal API before it starts listening.
Pick Encore when the WebSocket endpoint is part of a larger Go backend, and you want the auth handler, the secrets and the services that publish updates declared in the same code and deployed to your own AWS or GCP account. Pick net/http with gorilla/websocket when you already have a plain Go service and its deployment, and plan for the session check, the load balancer idle timeout and cross-instance fan-out yourself. In both cases, if the browser only receives updates and never sends, server-sent events are a simpler protocol to run.
The standard library has no WebSocket server, so most Go services use github.com/coder/websocket or github.com/gorilla/websocket. coder/websocket takes a context on every read and write and allows concurrent writes; gorilla/websocket allows one reader and one writer at a time, so you run a read loop and a write loop per connection.
Authenticate the HTTP upgrade request before you accept it. Browsers cannot set an Authorization header on a WebSocket, so read a session cookie or a short-lived ticket from the handshake request, reject it with 401 if it does not verify, and check the Origin header so other sites cannot open the socket with the user's cookie.
Declare a raw endpoint with //encore:api auth raw method=GET path=/live, call websocket.Accept from github.com/coder/websocket inside it, and read the caller from auth.Data(), which the auth handler filled from the session cookie. encore run serves the endpoint locally, and other services push updates by calling a private endpoint that broadcasts to the open connections.
Each instance only holds its own connections, so publish the message somewhere every instance listens. Postgres LISTEN/NOTIFY works for small payloads up to 8000 bytes, and a broker that delivers to every instance works for larger volumes. Each instance then writes the message to its local connections.
Deploy to your cloud on AWS and Google Cloud
without managing infrastructure
Encore lets developers and agents define application infrastructure directly in code, then automatically provisions it from local development to production in your AWS or GCP account.