Documentation

Build a party game

From go get to a phone joining your room in a few minutes.

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 your Game on 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 LocalConn for in-process clients. Seats outlive connections: a dropped client keeps its seat for ReconnectGrace (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

  1. Don't block in hooks. Don't use mutexes, sleeps or network calls. Use r.After for delays, and a goroutine plus room.Do for slow work.
  2. Send copies, not live state. In-process clients receive the exact value you pass. Build a fresh view struct for each send.
  3. No nil slices or maps in views. They become JSON null and break the browser.
  4. Secrets need per-client sends. Loop over r.Clients() and r.Send each one their own view.
  5. Validate everything. Check who sent it (c.ID, c.Role), whose turn it is, and whether m.Decode succeeded.

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:

Configuration

FieldDefault
NewGamerequiredReturns the game for a room; kind comes from the create request.
Storenil (memory)Persistence.
MaxPlayers8Per room; displays don't count.
CodeLength4Consonants only.
ReconnectGrace2mHow long a dropped client keeps its seat.
IdleTimeout10mClose rooms nobody is connected to.
RateLimit30/minCreates and joins per IP.
MessageRate / MessageBurst20/s, 40Per connection; excess closes with 1008.
MaxMessageBytes32 KiBPer incoming message.
PingInterval30sKeepalive through proxies.
ClientIPRemoteAddrUse 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.

DirectionTypeData
server → clientlobby.welcome{protocol, code, game, you}
server → clientlobby.state{code, vip, locked, clients[]}
server → clientlobby.error{error}
client → serverlobby.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.