How thevoid12/brainwars works
Project Type and Purpose
• This is a full-stack, real-time quiz game (“brainwars”) implemented as a monolithic Go service that serves both UI assets and JSON/WebSocket APIs.
• Users can sign in, create/join quiz rooms (with up to 10 players or bots), answer questions in real time, and view a live leaderboard. Planned v2 features include Redis-backed pub/sub, global matchmaking, sharing scores, and chat.
File-Structure Analysis
• Top-level:
• main.go, go.mod/sum – entrypoint and dependencies
• web/ – HTTP handlers, middleware, static UI templates & assets
• pkg/ – core business-logic packages (auth, users, quiz, room, bots, rate_limit, websocket, db, logger, util)
• config/ – JSON config files per environment
• migrations/ – SQL migration scripts + helper
• deployment/ – Docker, systemd, shell scripts, nginx config
• Patterns:
• Layered architecture (HTTP → handlers → services → data-access layer)
• SQL code generation (sqlc) under pkg/db/sqlc and custom dbal adapters
• WebSocket pub/sub in pkg/websocket for real-time updates
Key README Insights
• Environment variables configure Postgres connection
• v1 uses in-memory maps for state sync; v2 will introduce Redis Pub/Sub to sync across instances
• Bots implemented as timed answer generators
Main Components
a. Client Layer
• Web UI (HTML/CSS/JS using Tailwind, served from web/ui)
• WebSocket client scripts (ws.js, game.js, etc.)
b. API Layer
• HTTP server (net/http or Gin) with middleware (auth, CSRF, rate-limit, context) in web/middleware
• Route handlers in web/routes and web/ui/handlers
c. Business Logic Layer
• Auth service (pkg/auth)
• User service (pkg/users)
• Room service (pkg/room)
• Quiz service (pkg/quiz + prompt_service)
• Rate-limit service (pkg/rate_limit)
• Bot service (pkg/bots)
• WebSocket event service (pkg/websocket/event_service)
d. Data Layer
• PostgreSQL via pkg/db/db.go and pkg/db/dbal or sqlc packages
• (v2) Redis Pub/Sub for inter-instance messaging
e. External/Infrastructure
• LLM API for question generation
• Docker containers, nginx reverse proxy, systemd service
Relationships & Flows
• Browser UI → HTTP(S) → API handlers → service layer → database
• Browser UI ↔ WebSocket ↔ WebSocket service → event dispatcher → service layer → broadcast → Browser UI
• Services call pkg/db for CRUD and complex queries (via sqlc-generated code)
• Bot service schedules answer events back through the same WebSocket channel
• (v2) Multiple instances synchronize room state & events via Redis Pub/Sub
Architectural Patterns & Design Principles
• Layered separation (UI / HTTP / Services / Data)
• Single monolith with clearly separated packages
• Dependency injection for database and config
• Use of generated code for consistency (sqlc)
• Middleware funnel for cross-cutting concerns (auth, rate-limiting, CSRF)
• Event-driven real-time updates via WebSockets