Getting started
Install the package (Go 1.26 or newer):
go get github.com/immannino/lobby
Or run the finished buzzer game first, then open it on a laptop and a phone:
go run github.com/immannino/lobby/examples/quickstart@latest
The whole server:
package main
import (
"context"
_ "embed"
"log"
"net/http"
"github.com/immannino/lobby"
)
// buzzer is the whole game. Its methods run one at a time on the room's
// goroutine, so plain fields are safe without locks.
type buzzer struct {
lobby.BaseGame
winner string // name of the first player to buzz, "" while open
}
func (b *buzzer) OnConnect(ctx context.Context, r *lobby.Room, c lobby.Client) {
r.Send(c.ID, "buzz", b.winner) // catch up anyone who (re)connects
}
func (b *buzzer) OnMessage(ctx context.Context, r *lobby.Room, c lobby.Client, m lobby.Message) {
switch {
case m.Type == "buzz" && b.winner == "" && c.Role == lobby.RolePlayer:
b.winner = c.Name
case m.Type == "reset" && c.ID == r.VIP():
b.winner = ""
default:
return
}
r.Broadcast("buzz", b.winner)
}
//go:embed index.html
var page []byte
func main() {
m := lobby.New(lobby.Config{
NewGame: func(code, kind string) (lobby.Game, error) { return &buzzer{}, nil },
})
http.Handle("/api/", http.StripPrefix("/api", m.Handler()))
http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) { w.Write(page) })
log.Println("open http://localhost:8080")
log.Fatal(http.ListenAndServe(":8080", nil))
}
Handler() serves the HTTP API and the browser client, /client.js. Mount it under any prefix.
Concepts
- Room
- A game session with a short code such as
BCDF. Each room runs yourGameon its own goroutine. - Client
- A seat in a room. A player is a phone, with a name, and counts toward
MaxPlayers. A display is the big screen. - VIP
- The earliest-joined player. They can kick people and lock the room, and they move to the next player when they leave.
- Token
- Joining returns a random token, also set as an HttpOnly cookie. Only its hash is stored. Reconnecting with it reclaims the seat, even after a server restart.
- Connection
- A websocket, or a
LocalConnfor in-process clients. Seats outlive connections: a dropped client keeps its seat forReconnectGrace(2 minutes).
Writing a game
Embed lobby.BaseGame and override the hooks you need. Hooks run one at a time on the room's goroutine, so game state is plain fields.
type Game interface {
OnJoin(ctx context.Context, r *Room, c Client) // took a seat
OnLeave(ctx context.Context, r *Room, c Client) // seat gone: left, kicked, or expired
OnConnect(ctx context.Context, r *Room, c Client) // a connection attached; send a snapshot
OnDisconnect(ctx context.Context, r *Room, c Client) // dropped; seat kept for now
OnMessage(ctx context.Context, r *Room, c Client, m Message)
}
Inside a hook, talk to the room:
r.Broadcast("view", v) // everyone (JSON-encoded once)
r.SendRole(lobby.RoleDisplay, "view", v)
r.Send(c.ID, "error", map[string]string{"error": "not your turn"})
stop := r.After(20*time.Second, func(ctx context.Context, r *lobby.Room) { /* time's up */ })
r.SetLocked(ctx, true) // no new players mid-round
r.Persist(ctx) // save now, if a Store is configured
From outside a hook, such as an HTTP handler or a goroutine, use room.Do(ctx, func(ctx context.Context, r *lobby.Room) { ... }).
Rules that keep games correct
- Don't block in hooks. Don't use mutexes, sleeps or network calls. Use
r.Afterfor delays, and a goroutine plusroom.Dofor slow work. - Send copies, not live state. In-process clients receive the exact value you pass. Build a fresh view struct for each send.
- No nil slices or maps in views. They become JSON
nulland break the browser. - Secrets need per-client sends. Loop over
r.Clients()andr.Sendeach one their own view. - Validate everything. Check who sent it (
c.ID,c.Role), whose turn it is, and whetherm.Decodesucceeded.
Browser client
import { createRoom, joinRoom, connect } from "/api/client.js";
const { code } = await createRoom("/api", { name: "Ada", game: "trivia" }); // or { role: "display" }
const room = connect("/api", code, {
onMessage({ type, data }) { /* lobby.welcome, lobby.state, then your types */ },
onStatus(status, detail) { /* "open" | "reconnecting" | "closed" */ },
});
room.send("answer", 2);
room.kick(id); room.lock(true); room.leave();
It reconnects with backoff, and immediately when a phone wakes up. It stops on terminal close codes: kicked, room closed, or replaced by another tab.
Testing
lobbytest plays your game with in-process clients. There's no server, and you assert on your own Go types:
func TestBuzz(t *testing.T) {
m := lobbytest.Manager(t, func() lobby.Game { return &buzzer{} })
ada, code := lobbytest.Create(t, m, "Ada")
bob := lobbytest.Join(t, m, code, "Bob")
lobbytest.Send(t, bob, "buzz", nil)
if got := lobbytest.Wait(t, ada, func(s string) bool { return s != "" }); got != "Bob" {
t.Fatalf("winner = %q", got)
}
}
Computer players use the same mechanism. See examples/games/botkit.
Persistence
Rooms live in memory by default. To survive restarts, add a store and implement Snapshotter (Snapshot() ([]byte, error), Restore([]byte) error) on your game:
store, err := sqlitestore.Open(ctx, "lobby.db") // pure Go, no cgo
m := lobby.New(lobby.Config{NewGame: newGame, Store: store})
if err := m.Restore(ctx); err != nil { ... } // at startup
defer m.Shutdown(ctx) // persists rooms, tells clients to reconnect
For Postgres or MySQL, implement the three-method lobby.Store interface. See docs/storage.md.
Running in production
Where and how you host your server is up to you. These are the parts of the library that interact with that choice:
- Don't set
http.Server.WriteTimeout. It kills long-lived websockets. UseReadHeaderTimeoutinstead. - One process owns its rooms. Live connections are held in memory, so every request for a room code must reach the process hosting it.
- Behind a reverse proxy, set
ClientIP(for examplelobby.HeaderClientIP("X-Real-IP")) so rate limits apply per client, not per proxy. SetSecureCookieswhen serving HTTPS, andOriginPatternsif pages on another origin connect. - Call
m.Shutdown(ctx)onSIGTERM. It persists every room and closes sockets with "going away", so clients reconnect to the next process and keep their seats. Callm.Restore(ctx)at startup. - Monitor
m.Stats()for rooms, connections, messages, slow-client drops, rate limits and recovered panics.
Configuration
| Field | Default | |
|---|---|---|
NewGame | required | Returns the game for a room; kind comes from the create request. |
Store | nil (memory) | Persistence. |
MaxPlayers | 8 | Per room; displays don't count. |
CodeLength | 4 | Consonants only. |
ReconnectGrace | 2m | How long a dropped client keeps its seat. |
IdleTimeout | 10m | Close rooms nobody is connected to. |
RateLimit | 30/min | Creates and joins per IP. |
MessageRate / MessageBurst | 20/s, 40 | Per connection; excess closes with 1008. |
MaxMessageBytes | 32 KiB | Per incoming message. |
PingInterval | 30s | Keepalive through proxies. |
ClientIP | RemoteAddr | Use lobby.HeaderClientIP("X-Real-IP") behind a proxy. |
OriginPatterns, SecureCookies, Logger |
m.Stats() returns counters for rooms, connections, messages, drops, rate limits and panics, ready for expvar or Prometheus.
Wire protocol
Every websocket frame is {"type": "...", "data": ...}. Types starting with lobby. are reserved.
| Direction | Type | Data |
|---|---|---|
| server → client | lobby.welcome | {protocol, code, game, you} |
| server → client | lobby.state | {code, vip, locked, clients[]} |
| server → client | lobby.error | {error} |
| client → server | lobby.leave · lobby.kick {id} · lobby.lock {locked} | kick and lock: VIP only |
Terminal close codes: 4401 unauthorized, 4403 kicked, 4404 not found, 4409 replaced, 4410 room closed. Anything else means reconnect.
HTTP: POST /rooms, GET /rooms/{code}, POST /rooms/{code}/join, GET /rooms/{code}/ws, GET /client.js.
Using with AI agents
The repository includes AGENTS.md, a guide written for coding agents. It covers a minimal integration, the Game contract, the rules above, recipes for bots, two-player games and tests, and a table of common mistakes. Most agents read it automatically. Otherwise, point yours at it and ask for a game.