Compare commits
1 Commits
main
...
729db559ea
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
729db559ea |
@@ -11,10 +11,6 @@
|
|||||||
# PORT=7331
|
# PORT=7331
|
||||||
|
|
||||||
# Goose CLI migration config (only needed for running goose manually)
|
# Goose CLI migration config (only needed for running goose manually)
|
||||||
# Gitea API token for downloading datastar-pro from private repo (CI/Docker only).
|
|
||||||
# Not needed for local dev — falls back to copying from ../optional/.
|
|
||||||
# VENDOR_TOKEN=
|
|
||||||
|
|
||||||
GOOSE_DRIVER=sqlite3
|
GOOSE_DRIVER=sqlite3
|
||||||
GOOSE_DBSTRING=data/games.db?_pragma=foreign_keys(1)&_pragma=journal_mode(WAL)
|
GOOSE_DBSTRING=data/games.db?_pragma=foreign_keys(1)&_pragma=journal_mode(WAL)
|
||||||
GOOSE_MIGRATION_DIR=db/migrations
|
GOOSE_MIGRATION_DIR=db/migrations
|
||||||
|
|||||||
@@ -61,13 +61,8 @@ jobs:
|
|||||||
mkdir -p $DEPLOY_DIR/data
|
mkdir -p $DEPLOY_DIR/data
|
||||||
|
|
||||||
- name: Rebuild and restart
|
- name: Rebuild and restart
|
||||||
env:
|
|
||||||
VENDOR_TOKEN: ${{ secrets.VENDOR_TOKEN }}
|
|
||||||
run: |
|
run: |
|
||||||
cd $DEPLOY_DIR
|
cd $DEPLOY_DIR
|
||||||
VERSION=$(git describe --tags --always)
|
VERSION=$(git describe --tags --always)
|
||||||
COMMIT=$(git rev-parse --short HEAD)
|
COMMIT=$(git rev-parse --short HEAD)
|
||||||
VERSION=$VERSION COMMIT=$COMMIT VENDOR_TOKEN=$VENDOR_TOKEN docker compose up -d --build --remove-orphans
|
VERSION=$VERSION COMMIT=$COMMIT docker compose up -d --build --remove-orphans
|
||||||
|
|
||||||
- name: Prune unused images
|
|
||||||
run: docker image prune -f
|
|
||||||
|
|||||||
5
.gitignore
vendored
5
.gitignore
vendored
@@ -19,7 +19,6 @@
|
|||||||
|
|
||||||
!.env.example
|
!.env.example
|
||||||
!LICENSE
|
!LICENSE
|
||||||
!AGENTS.md
|
|
||||||
|
|
||||||
!assets/**/*
|
!assets/**/*
|
||||||
|
|
||||||
@@ -27,10 +26,6 @@
|
|||||||
*_templ.go
|
*_templ.go
|
||||||
assets/css/output.css
|
assets/css/output.css
|
||||||
|
|
||||||
# Downloaded client-side libs (fetched by cmd/downloader)
|
|
||||||
assets/js/datastar/*
|
|
||||||
assets/css/daisyui/*
|
|
||||||
|
|
||||||
# Deploy scripts and configs
|
# Deploy scripts and configs
|
||||||
!deploy/*.sh
|
!deploy/*.sh
|
||||||
!deploy/*.service
|
!deploy/*.service
|
||||||
|
|||||||
218
AGENTS.md
218
AGENTS.md
@@ -1,218 +0,0 @@
|
|||||||
# AGENTS.md
|
|
||||||
|
|
||||||
Instructions for AI coding agents working in this repository.
|
|
||||||
|
|
||||||
## Quick Reference
|
|
||||||
|
|
||||||
```bash
|
|
||||||
# Development
|
|
||||||
task live # Hot-reload dev server (templ + tailwind + air)
|
|
||||||
task build # Production build to bin/games
|
|
||||||
task run # Build and run server
|
|
||||||
task download # Download pinned client-side libs (datastar-pro, daisyui)
|
|
||||||
|
|
||||||
# Quality
|
|
||||||
task test # Run all tests: go test ./...
|
|
||||||
task lint # Run linter: golangci-lint run
|
|
||||||
|
|
||||||
# Single test
|
|
||||||
go test -run TestName ./path/to/package
|
|
||||||
go test -v -run TestHandleLogin_Success ./features/auth
|
|
||||||
|
|
||||||
# Code generation
|
|
||||||
task build:templ # Compile .templ files (go tool templ generate)
|
|
||||||
task build:styles # Build TailwindCSS (go tool gotailwind)
|
|
||||||
```
|
|
||||||
|
|
||||||
Tools (templ, air, gotailwind, goose, sqlc) are managed via Go 1.25's `tool` directive in go.mod — no separate installs needed.
|
|
||||||
|
|
||||||
## Workflow Rules
|
|
||||||
|
|
||||||
- **Never merge PRs without explicit user approval.** Create the PR, push changes, then wait.
|
|
||||||
- Always use PRs via `tea` CLI — never push directly to main.
|
|
||||||
- Write semantic commit messages focusing on "why" not "what".
|
|
||||||
|
|
||||||
## Project Structure
|
|
||||||
|
|
||||||
```
|
|
||||||
games/
|
|
||||||
├── connect4/, snake/ # Game logic packages (pure Go, no HTTP)
|
|
||||||
├── features/ # Feature modules (handlers, routes, templates)
|
|
||||||
│ ├── auth/ # Login/register (standard HTTP, not SSE)
|
|
||||||
│ ├── c4game/ # Connect 4 UI + services
|
|
||||||
│ ├── snakegame/ # Snake UI + services
|
|
||||||
│ ├── lobby/ # Game lobby
|
|
||||||
│ └── common/ # Shared components, layouts
|
|
||||||
├── chat/ # Reusable chat room (NATS + optional DB persistence)
|
|
||||||
├── auth/ # Password hashing/validation (pure, no HTTP)
|
|
||||||
├── db/ # SQLite, migrations, sqlc queries
|
|
||||||
├── cmd/downloader/ # Build-time tool: fetches datastar-pro + daisyui
|
|
||||||
├── assets/ # Static files (embedded in prod, filesystem in dev)
|
|
||||||
└── config/, logging/, nats/, sessions/, router/, player/, version/
|
|
||||||
```
|
|
||||||
|
|
||||||
## Code Style
|
|
||||||
|
|
||||||
### Imports
|
|
||||||
|
|
||||||
Three groups separated by blank lines: stdlib, third-party, local. Enforced by goimports with `local-prefixes: github.com/ryanhamamura/games`.
|
|
||||||
|
|
||||||
```go
|
|
||||||
import (
|
|
||||||
"fmt"
|
|
||||||
"net/http"
|
|
||||||
|
|
||||||
"github.com/go-chi/chi/v5"
|
|
||||||
|
|
||||||
"github.com/ryanhamamura/games/connect4"
|
|
||||||
)
|
|
||||||
```
|
|
||||||
|
|
||||||
### Error Handling
|
|
||||||
|
|
||||||
```go
|
|
||||||
// Wrap errors with context
|
|
||||||
return fmt.Errorf("loading game %s: %w", id, err)
|
|
||||||
|
|
||||||
// Combine cleanup errors with errors.Join
|
|
||||||
return nil, errors.Join(fmt.Errorf("pinging database: %w", err), DB.Close())
|
|
||||||
|
|
||||||
// Best-effort operations
|
|
||||||
nc.Publish(subject, nil) //nolint:errcheck // best-effort notification
|
|
||||||
|
|
||||||
// HTTP errors
|
|
||||||
http.Error(w, "game not found", http.StatusNotFound)
|
|
||||||
http.Error(w, http.StatusText(http.StatusInternalServerError), http.StatusInternalServerError)
|
|
||||||
|
|
||||||
```
|
|
||||||
|
|
||||||
### Comments
|
|
||||||
|
|
||||||
- Focus on **why**, not **how**. Avoid superfluous comments.
|
|
||||||
- Package comments at top of primary file.
|
|
||||||
- Function comments for exported functions.
|
|
||||||
|
|
||||||
## Go Patterns
|
|
||||||
|
|
||||||
### Dependency Injection via Closures
|
|
||||||
|
|
||||||
Handlers receive dependencies and return `http.HandlerFunc`:
|
|
||||||
|
|
||||||
```go
|
|
||||||
func HandleGamePage(store *connect4.Store, sm *scs.SessionManager) http.HandlerFunc {
|
|
||||||
return func(w http.ResponseWriter, r *http.Request) { /* ... */ }
|
|
||||||
}
|
|
||||||
```
|
|
||||||
|
|
||||||
### Cleanup Function Returns
|
|
||||||
|
|
||||||
Infrastructure init functions return a cleanup func the caller defers:
|
|
||||||
|
|
||||||
```go
|
|
||||||
cleanupDB, err := db.Init(cfg.DBPath)
|
|
||||||
defer cleanupDB()
|
|
||||||
```
|
|
||||||
|
|
||||||
### Store/Instance Pattern
|
|
||||||
|
|
||||||
Game state uses a two-tier pattern: a thread-safe **Store** (map + RWMutex) holding **Instance** wrappers (individual game + own mutex + DB queries). Stores lazy-load from DB on cache miss.
|
|
||||||
|
|
||||||
### Build Tags
|
|
||||||
|
|
||||||
`//go:build dev` and `//go:build !dev` switch behavior for static asset serving (filesystem vs embedded hashfs) and config loading.
|
|
||||||
|
|
||||||
## Templ + Datastar Patterns
|
|
||||||
|
|
||||||
### Architecture: Everything Is a Stream
|
|
||||||
|
|
||||||
The core mental model: **the server owns all state and continuously projects it to the browser over SSE**. There is no client-side state management. The browser connects to an event stream, and the server pushes full HTML fragments whenever something changes. Datastar morphs these into the DOM — the client is a thin rendering surface.
|
|
||||||
|
|
||||||
User actions (clicks, keypresses) trigger short POST/DELETE requests back to the server. The server mutates state, publishes a NATS signal, and every connected SSE stream picks up the change and re-renders. The client never needs to know what changed — it just receives the new truth and morphs to match.
|
|
||||||
|
|
||||||
This means: **always send whole components down the wire.** Don't try to diff or send minimal patches. Render the full templ component, call `sse.PatchElementTempl()`, and let Datastar's morph handle the rest. The only exception is appending to a list (e.g. chat messages).
|
|
||||||
|
|
||||||
**Signals follow command-query segregation.** Signals are *commands* — they carry the user's intent to the server (form input values, button clicks). The SSE stream is the *query* — it continuously projects the server's truth into the DOM. Keep signals thin: form input buffers (`chatMsg`, `nickname`), pure UI state the server never needs (`activeTab`), and request indicators. Don't use signals to hold application state — that arrives from the server via SSE.
|
|
||||||
|
|
||||||
### SSE Event Loop
|
|
||||||
|
|
||||||
Both game event handlers follow the same structure:
|
|
||||||
1. Subscribe to NATS channels **before** creating SSE (avoids missed messages)
|
|
||||||
2. Send initial full-state patch
|
|
||||||
3. `select` loop over: context done, game updates (drain channel first), chat messages (append), 1-second heartbeat (full re-render)
|
|
||||||
|
|
||||||
```go
|
|
||||||
// Handler side — long-lived SSE with Brotli compression
|
|
||||||
sse := datastar.NewSSE(w, r, datastar.WithCompression(
|
|
||||||
datastar.WithBrotli(datastar.WithBrotliLevel(5)),
|
|
||||||
))
|
|
||||||
sse.PatchElementTempl(components.GameBoard(game))
|
|
||||||
|
|
||||||
// Template side — disable Datastar's default SSE cancellation on interaction
|
|
||||||
data-init={ fmt.Sprintf("@get('/games/%s/events',{requestCancellation:'disabled'})", g.ID) }
|
|
||||||
```
|
|
||||||
|
|
||||||
### Client-Server Interactions
|
|
||||||
|
|
||||||
```go
|
|
||||||
// Trigger SSE actions from templates
|
|
||||||
data-on:click={ datastar.PostSSE("/games/%s/drop?col=%d", g.ID, colIdx) }
|
|
||||||
data-on:click={ datastar.DeleteSSE("/games/%s", g.ID) }
|
|
||||||
|
|
||||||
// Read client signals in handlers
|
|
||||||
var signals struct { ChatMsg string `json:"chatMsg"` }
|
|
||||||
datastar.ReadSignals(r, &signals)
|
|
||||||
|
|
||||||
// Clear input after submission
|
|
||||||
sse.MarshalAndPatchSignals(map[string]any{"chatMsg": ""})
|
|
||||||
|
|
||||||
// Redirect via SSE
|
|
||||||
sse.Redirectf("/games/%s", newGame.ID())
|
|
||||||
```
|
|
||||||
|
|
||||||
### Appending Elements (Chat Messages)
|
|
||||||
|
|
||||||
The one exception to whole-component morphing is chat, where messages are appended individually:
|
|
||||||
|
|
||||||
```go
|
|
||||||
sse.PatchElementTempl(
|
|
||||||
chatcomponents.ChatMessage(msg, cfg),
|
|
||||||
datastar.WithSelectorID("c4-chat-history"),
|
|
||||||
datastar.WithModeAppend(),
|
|
||||||
)
|
|
||||||
```
|
|
||||||
|
|
||||||
### Datastar Template Attributes
|
|
||||||
|
|
||||||
- `data-signals` — declare reactive state
|
|
||||||
- `data-bind` — two-way input binding
|
|
||||||
- `data-show` — conditional visibility
|
|
||||||
- `data-class` — reactive CSS classes
|
|
||||||
- `data-morph-ignore` — prevent SSE from overwriting an element (e.g. chat input)
|
|
||||||
|
|
||||||
## Testing
|
|
||||||
|
|
||||||
```bash
|
|
||||||
task test # All tests
|
|
||||||
go test -run TestHandleLogin_Success ./features/auth # Single test
|
|
||||||
go test -v ./features/auth # Verbose package
|
|
||||||
```
|
|
||||||
|
|
||||||
- Use `testutil.NewTestDB(t)` for tests needing a database
|
|
||||||
- Use `testutil.NewTestSessionManager(db)` for session-aware tests
|
|
||||||
- Use `config.LoadForTest()` to set safe defaults without .env
|
|
||||||
- Tests use external test packages (`package auth_test`)
|
|
||||||
|
|
||||||
## Tech Stack
|
|
||||||
|
|
||||||
| Layer | Technology |
|
|
||||||
|-------|------------|
|
|
||||||
| Templates | templ (type-safe HTML) |
|
|
||||||
| Reactivity | Datastar Pro (SSE-driven) |
|
|
||||||
| CSS | TailwindCSS v4 + daisyUI |
|
|
||||||
| Router | chi/v5 |
|
|
||||||
| Sessions | scs/v2 (SQLite-backed) |
|
|
||||||
| Database | SQLite (modernc.org/sqlite) |
|
|
||||||
| Migrations | goose (embedded SQL) |
|
|
||||||
| SQL codegen | sqlc |
|
|
||||||
| Pub/sub | Embedded NATS (nil-payload signals) |
|
|
||||||
| Logging | zerolog + slog (bridged via slog-zerolog) |
|
|
||||||
@@ -10,11 +10,6 @@ COPY go.mod go.sum ./
|
|||||||
RUN go mod download
|
RUN go mod download
|
||||||
|
|
||||||
COPY . .
|
COPY . .
|
||||||
|
|
||||||
RUN --mount=type=secret,id=vendor_token \
|
|
||||||
VENDOR_TOKEN=$(cat /run/secrets/vendor_token) \
|
|
||||||
go run cmd/downloader/main.go
|
|
||||||
|
|
||||||
RUN go tool templ generate
|
RUN go tool templ generate
|
||||||
RUN go tool gotailwind -i assets/css/input.css -o assets/css/output.css --minify
|
RUN go tool gotailwind -i assets/css/input.css -o assets/css/output.css --minify
|
||||||
RUN --mount=type=cache,target=/root/.cache/go-build \
|
RUN --mount=type=cache,target=/root/.cache/go-build \
|
||||||
|
|||||||
@@ -2,12 +2,9 @@ version: "3"
|
|||||||
|
|
||||||
tasks:
|
tasks:
|
||||||
download:
|
download:
|
||||||
desc: Download pinned client-side libs
|
desc: Download latest client-side libs
|
||||||
cmds:
|
cmds:
|
||||||
- go run cmd/downloader/main.go
|
- go run cmd/downloader/main.go
|
||||||
status:
|
|
||||||
- test -f assets/js/datastar/datastar.js
|
|
||||||
- test -f assets/css/daisyui/daisyui.js
|
|
||||||
|
|
||||||
build:templ:
|
build:templ:
|
||||||
desc: Compile .templ files to Go
|
desc: Compile .templ files to Go
|
||||||
@@ -34,7 +31,6 @@ tasks:
|
|||||||
cmds:
|
cmds:
|
||||||
- go build -o bin/games .
|
- go build -o bin/games .
|
||||||
deps:
|
deps:
|
||||||
- download
|
|
||||||
- build:templ
|
- build:templ
|
||||||
- build:styles
|
- build:styles
|
||||||
|
|
||||||
@@ -62,7 +58,6 @@ tasks:
|
|||||||
live:
|
live:
|
||||||
desc: Dev mode with hot-reload
|
desc: Dev mode with hot-reload
|
||||||
deps:
|
deps:
|
||||||
- download
|
|
||||||
- live:templ
|
- live:templ
|
||||||
- live:styles
|
- live:styles
|
||||||
- live:server
|
- live:server
|
||||||
|
|||||||
@@ -1,5 +0,0 @@
|
|||||||
// Package assets provides static file serving with build-tag switching
|
|
||||||
// between live filesystem (dev) and embedded hashfs (prod).
|
|
||||||
package assets
|
|
||||||
|
|
||||||
const DirectoryPath = "assets"
|
|
||||||
93
assets/css/daisyui-theme.mjs
Normal file
93
assets/css/daisyui-theme.mjs
Normal file
File diff suppressed because one or more lines are too long
1026
assets/css/daisyui.mjs
Normal file
1026
assets/css/daisyui.mjs
Normal file
File diff suppressed because one or more lines are too long
@@ -1,8 +1,8 @@
|
|||||||
@import 'tailwindcss';
|
@import 'tailwindcss';
|
||||||
|
|
||||||
@source not "./daisyui/daisyui{,*}.js";
|
@source not "./daisyui{,*}.mjs";
|
||||||
@plugin "./daisyui/daisyui.js";
|
@plugin "./daisyui.mjs";
|
||||||
@plugin "./daisyui/daisyui-theme.js" {
|
@plugin "./daisyui-theme.mjs" {
|
||||||
name: "stealth";
|
name: "stealth";
|
||||||
default: true;
|
default: true;
|
||||||
color-scheme: light;
|
color-scheme: light;
|
||||||
|
|||||||
File diff suppressed because one or more lines are too long
@@ -1 +0,0 @@
|
|||||||
Downloaded by cmd/downloader at build time.
|
|
||||||
9
assets/js/datastar.js
Normal file
9
assets/js/datastar.js
Normal file
File diff suppressed because one or more lines are too long
7
assets/js/datastar.js.map
Normal file
7
assets/js/datastar.js.map
Normal file
File diff suppressed because one or more lines are too long
@@ -1,22 +0,0 @@
|
|||||||
//go:build dev
|
|
||||||
|
|
||||||
package assets
|
|
||||||
|
|
||||||
import (
|
|
||||||
"net/http"
|
|
||||||
"os"
|
|
||||||
|
|
||||||
"github.com/rs/zerolog/log"
|
|
||||||
)
|
|
||||||
|
|
||||||
func Handler() http.Handler {
|
|
||||||
log.Debug().Str("path", DirectoryPath).Msg("static assets served from filesystem")
|
|
||||||
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
|
||||||
w.Header().Set("Cache-Control", "no-store")
|
|
||||||
http.StripPrefix("/assets/", http.FileServerFS(os.DirFS(DirectoryPath))).ServeHTTP(w, r)
|
|
||||||
})
|
|
||||||
}
|
|
||||||
|
|
||||||
func StaticPath(path string) string {
|
|
||||||
return "/assets/" + path
|
|
||||||
}
|
|
||||||
@@ -1,26 +0,0 @@
|
|||||||
//go:build !dev
|
|
||||||
|
|
||||||
package assets
|
|
||||||
|
|
||||||
import (
|
|
||||||
"embed"
|
|
||||||
"net/http"
|
|
||||||
|
|
||||||
"github.com/benbjohnson/hashfs"
|
|
||||||
"github.com/rs/zerolog/log"
|
|
||||||
)
|
|
||||||
|
|
||||||
var (
|
|
||||||
//go:embed css js
|
|
||||||
staticFiles embed.FS
|
|
||||||
staticSys = hashfs.NewFS(staticFiles)
|
|
||||||
)
|
|
||||||
|
|
||||||
func Handler() http.Handler {
|
|
||||||
log.Debug().Msg("static assets are embedded with hashfs")
|
|
||||||
return http.StripPrefix("/assets/", hashfs.FileServer(staticSys))
|
|
||||||
}
|
|
||||||
|
|
||||||
func StaticPath(path string) string {
|
|
||||||
return "/assets/" + staticSys.HashName(path)
|
|
||||||
}
|
|
||||||
42
chat/chat.go
42
chat/chat.go
@@ -76,11 +76,12 @@ func (r *Room) Send(msg Message) {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// receive processes an incoming NATS message, appending it to the buffer.
|
// Receive processes an incoming NATS message, appending it to the buffer.
|
||||||
func (r *Room) receive(data []byte) (Message, bool) {
|
// Returns the new message and a snapshot of all messages.
|
||||||
|
func (r *Room) Receive(data []byte) (Message, []Message) {
|
||||||
var msg Message
|
var msg Message
|
||||||
if err := json.Unmarshal(data, &msg); err != nil {
|
if err := json.Unmarshal(data, &msg); err != nil {
|
||||||
return msg, false
|
return msg, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
r.mu.Lock()
|
r.mu.Lock()
|
||||||
@@ -88,9 +89,11 @@ func (r *Room) receive(data []byte) (Message, bool) {
|
|||||||
if len(r.messages) > maxMessages {
|
if len(r.messages) > maxMessages {
|
||||||
r.messages = r.messages[len(r.messages)-maxMessages:]
|
r.messages = r.messages[len(r.messages)-maxMessages:]
|
||||||
}
|
}
|
||||||
|
snapshot := make([]Message, len(r.messages))
|
||||||
|
copy(snapshot, r.messages)
|
||||||
r.mu.Unlock()
|
r.mu.Unlock()
|
||||||
|
|
||||||
return msg, true
|
return msg, snapshot
|
||||||
}
|
}
|
||||||
|
|
||||||
// Messages returns a snapshot of the current message buffer.
|
// Messages returns a snapshot of the current message buffer.
|
||||||
@@ -102,32 +105,15 @@ func (r *Room) Messages() []Message {
|
|||||||
return snapshot
|
return snapshot
|
||||||
}
|
}
|
||||||
|
|
||||||
// Subscribe returns a channel of parsed messages and a cleanup function.
|
// Subscribe creates a NATS channel subscription for the room's subject.
|
||||||
// The room handles NATS subscription internally and buffers messages.
|
// Caller is responsible for unsubscribing.
|
||||||
func (r *Room) Subscribe() (<-chan Message, func()) {
|
func (r *Room) Subscribe() (chan *nats.Msg, *nats.Subscription, error) {
|
||||||
natsCh := make(chan *nats.Msg, 64)
|
ch := make(chan *nats.Msg, 64)
|
||||||
msgCh := make(chan Message, 64)
|
sub, err := r.nc.ChanSubscribe(r.subject, ch)
|
||||||
|
|
||||||
sub, err := r.nc.ChanSubscribe(r.subject, natsCh)
|
|
||||||
if err != nil {
|
if err != nil {
|
||||||
close(msgCh)
|
return nil, nil, err
|
||||||
return msgCh, func() {}
|
|
||||||
}
|
}
|
||||||
|
return ch, sub, nil
|
||||||
go func() {
|
|
||||||
for natsMsg := range natsCh {
|
|
||||||
if msg, ok := r.receive(natsMsg.Data); ok {
|
|
||||||
msgCh <- msg
|
|
||||||
}
|
|
||||||
}
|
|
||||||
close(msgCh)
|
|
||||||
}()
|
|
||||||
|
|
||||||
cleanup := func() {
|
|
||||||
_ = sub.Unsubscribe()
|
|
||||||
}
|
|
||||||
|
|
||||||
return msgCh, cleanup
|
|
||||||
}
|
}
|
||||||
|
|
||||||
func (r *Room) saveMessage(msg Message) {
|
func (r *Room) saveMessage(msg Message) {
|
||||||
|
|||||||
@@ -1,20 +1,30 @@
|
|||||||
package main
|
package main
|
||||||
|
|
||||||
import (
|
import (
|
||||||
"encoding/json"
|
|
||||||
"errors"
|
"errors"
|
||||||
"fmt"
|
"fmt"
|
||||||
"io"
|
"io"
|
||||||
"log/slog"
|
"log/slog"
|
||||||
"net/http"
|
"net/http"
|
||||||
"net/url"
|
|
||||||
"os"
|
"os"
|
||||||
"path/filepath"
|
"path/filepath"
|
||||||
"sync"
|
"sync"
|
||||||
|
|
||||||
"github.com/ryanhamamura/games/assets"
|
|
||||||
)
|
)
|
||||||
|
|
||||||
|
// Asset directories, relative to project root.
|
||||||
|
const (
|
||||||
|
jsDir = "assets/js"
|
||||||
|
cssDir = "assets/css"
|
||||||
|
)
|
||||||
|
|
||||||
|
// files maps download URLs to local destination paths.
|
||||||
|
var files = map[string]string{
|
||||||
|
"https://raw.githubusercontent.com/starfederation/datastar/main/bundles/datastar.js": jsDir + "/datastar.js",
|
||||||
|
"https://raw.githubusercontent.com/starfederation/datastar/main/bundles/datastar.js.map": jsDir + "/datastar.js.map",
|
||||||
|
"https://github.com/saadeghi/daisyui/releases/latest/download/daisyui.mjs": cssDir + "/daisyui.mjs",
|
||||||
|
"https://github.com/saadeghi/daisyui/releases/latest/download/daisyui-theme.mjs": cssDir + "/daisyui-theme.mjs",
|
||||||
|
}
|
||||||
|
|
||||||
func main() {
|
func main() {
|
||||||
if err := run(); err != nil {
|
if err := run(); err != nil {
|
||||||
slog.Error("failure", "error", err)
|
slog.Error("failure", "error", err)
|
||||||
@@ -22,243 +32,16 @@ func main() {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// Pinned dependency versions — update these to upgrade.
|
|
||||||
const (
|
|
||||||
datastarVersion = "v1.0.0-RC.8" // Pro build — fetched from private Gitea repo
|
|
||||||
daisyuiVersion = "v5.5.19"
|
|
||||||
)
|
|
||||||
|
|
||||||
// dependencies tracks pinned versions alongside their GitHub coordinates
|
|
||||||
// so the version check can look up the latest release for each.
|
|
||||||
var dependencies = []dependency{
|
|
||||||
{name: "datastar", owner: "starfederation", repo: "datastar", pinnedVersion: datastarVersion},
|
|
||||||
{name: "daisyui", owner: "saadeghi", repo: "daisyui", pinnedVersion: daisyuiVersion},
|
|
||||||
}
|
|
||||||
|
|
||||||
type dependency struct {
|
|
||||||
name string
|
|
||||||
owner string
|
|
||||||
repo string
|
|
||||||
pinnedVersion string
|
|
||||||
}
|
|
||||||
|
|
||||||
// datastar-pro sources, in order of preference.
|
|
||||||
const (
|
|
||||||
giteaRawURL = "https://gitea.adriatica.io/ryan/vendor-libs/raw/branch/main/datastar/datastar.js"
|
|
||||||
localFallbackPath = "../optional/web/resources/static/datastar/datastar.js"
|
|
||||||
)
|
|
||||||
|
|
||||||
func run() error {
|
func run() error {
|
||||||
jsDir := assets.DirectoryPath + "/js/datastar"
|
dirs := []string{jsDir, cssDir}
|
||||||
cssDir := assets.DirectoryPath + "/css/daisyui"
|
|
||||||
|
|
||||||
daisyuiBase := "https://github.com/saadeghi/daisyui/releases/download/" + daisyuiVersion + "/"
|
for _, dir := range dirs {
|
||||||
|
if err := os.MkdirAll(dir, 0755); err != nil {
|
||||||
downloads := map[string]string{
|
return fmt.Errorf("create directory %s: %w", dir, err)
|
||||||
daisyuiBase + "daisyui.js": cssDir + "/daisyui.js",
|
}
|
||||||
daisyuiBase + "daisyui-theme.js": cssDir + "/daisyui-theme.js",
|
|
||||||
}
|
}
|
||||||
|
|
||||||
directories := []string{jsDir, cssDir}
|
return download(files)
|
||||||
|
|
||||||
if err := removeDirectories(directories); err != nil {
|
|
||||||
return err
|
|
||||||
}
|
|
||||||
|
|
||||||
if err := createDirectories(directories); err != nil {
|
|
||||||
return err
|
|
||||||
}
|
|
||||||
|
|
||||||
if err := acquireDatastar(jsDir + "/datastar.js"); err != nil {
|
|
||||||
return err
|
|
||||||
}
|
|
||||||
|
|
||||||
if err := download(downloads); err != nil {
|
|
||||||
return err
|
|
||||||
}
|
|
||||||
|
|
||||||
checkForUpdates()
|
|
||||||
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
|
|
||||||
// acquireDatastar fetches datastar-pro from the private Gitea repo when
|
|
||||||
// GITEA_TOKEN is set, otherwise copies from the local optional project.
|
|
||||||
func acquireDatastar(dest string) error {
|
|
||||||
if token := os.Getenv("VENDOR_TOKEN"); token != "" {
|
|
||||||
slog.Info("downloading datastar-pro from private repo...")
|
|
||||||
return downloadWithAuth(giteaRawURL, dest, token)
|
|
||||||
}
|
|
||||||
|
|
||||||
slog.Info("copying datastar-pro from local fallback...", "src", localFallbackPath)
|
|
||||||
return copyFile(localFallbackPath, dest)
|
|
||||||
}
|
|
||||||
|
|
||||||
func copyFile(src, dest string) error {
|
|
||||||
in, err := os.Open(src) //nolint:gosec // paths are hardcoded constants
|
|
||||||
if err != nil {
|
|
||||||
return fmt.Errorf("open %s: %w", src, err)
|
|
||||||
}
|
|
||||||
defer in.Close() //nolint:errcheck
|
|
||||||
|
|
||||||
out, err := os.Create(dest) //nolint:gosec // paths are hardcoded constants
|
|
||||||
if err != nil {
|
|
||||||
return fmt.Errorf("create %s: %w", dest, err)
|
|
||||||
}
|
|
||||||
|
|
||||||
if _, err := io.Copy(out, in); err != nil {
|
|
||||||
out.Close() //nolint:errcheck
|
|
||||||
return fmt.Errorf("copy to %s: %w", dest, err)
|
|
||||||
}
|
|
||||||
|
|
||||||
if err := out.Close(); err != nil {
|
|
||||||
return fmt.Errorf("close %s: %w", dest, err)
|
|
||||||
}
|
|
||||||
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
|
|
||||||
func downloadWithAuth(rawURL, dest, token string) error {
|
|
||||||
req, err := http.NewRequest(http.MethodGet, rawURL, nil)
|
|
||||||
if err != nil {
|
|
||||||
return fmt.Errorf("create request for %s: %w", rawURL, err)
|
|
||||||
}
|
|
||||||
req.Header.Set("Authorization", "token "+token)
|
|
||||||
|
|
||||||
resp, err := http.DefaultClient.Do(req) //nolint:gosec // URL is built from compile-time constants
|
|
||||||
if err != nil {
|
|
||||||
return fmt.Errorf("GET %s: %w", rawURL, err)
|
|
||||||
}
|
|
||||||
defer resp.Body.Close() //nolint:errcheck
|
|
||||||
|
|
||||||
if resp.StatusCode != http.StatusOK {
|
|
||||||
return fmt.Errorf("GET %s: status %s", rawURL, resp.Status)
|
|
||||||
}
|
|
||||||
|
|
||||||
out, err := os.Create(dest) //nolint:gosec // paths are hardcoded constants
|
|
||||||
if err != nil {
|
|
||||||
return fmt.Errorf("create %s: %w", dest, err)
|
|
||||||
}
|
|
||||||
|
|
||||||
if _, err := io.Copy(out, resp.Body); err != nil {
|
|
||||||
out.Close() //nolint:errcheck
|
|
||||||
return fmt.Errorf("write %s: %w", dest, err)
|
|
||||||
}
|
|
||||||
|
|
||||||
if err := out.Close(); err != nil {
|
|
||||||
return fmt.Errorf("close %s: %w", dest, err)
|
|
||||||
}
|
|
||||||
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
|
|
||||||
// checkForUpdates queries the GitHub releases API for each dependency
|
|
||||||
// and logs a notice if a newer version is available. Failures are
|
|
||||||
// logged but never cause the download to fail.
|
|
||||||
func checkForUpdates() {
|
|
||||||
var wg sync.WaitGroup
|
|
||||||
|
|
||||||
for _, dep := range dependencies {
|
|
||||||
wg.Go(func() {
|
|
||||||
latest, err := latestGitHubRelease(dep.owner, dep.repo)
|
|
||||||
if err != nil {
|
|
||||||
slog.Warn("could not check for updates", "dependency", dep.name, "error", err)
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
if latest != dep.pinnedVersion {
|
|
||||||
slog.Warn("newer version available",
|
|
||||||
"dependency", dep.name,
|
|
||||||
"pinned", dep.pinnedVersion,
|
|
||||||
"latest", latest,
|
|
||||||
)
|
|
||||||
}
|
|
||||||
})
|
|
||||||
}
|
|
||||||
|
|
||||||
wg.Wait()
|
|
||||||
}
|
|
||||||
|
|
||||||
// githubRelease is the minimal subset of the GitHub releases API response we need.
|
|
||||||
type githubRelease struct {
|
|
||||||
TagName string `json:"tag_name"`
|
|
||||||
}
|
|
||||||
|
|
||||||
func latestGitHubRelease(owner, repo string) (string, error) {
|
|
||||||
u := &url.URL{
|
|
||||||
Scheme: "https",
|
|
||||||
Host: "api.github.com",
|
|
||||||
Path: fmt.Sprintf("/repos/%s/%s/releases/latest", owner, repo),
|
|
||||||
}
|
|
||||||
|
|
||||||
req, err := http.NewRequest(http.MethodGet, u.String(), nil)
|
|
||||||
if err != nil {
|
|
||||||
return "", fmt.Errorf("creating request: %w", err)
|
|
||||||
}
|
|
||||||
req.Header.Set("Accept", "application/vnd.github+json")
|
|
||||||
|
|
||||||
resp, err := http.DefaultClient.Do(req) //nolint:gosec
|
|
||||||
if err != nil {
|
|
||||||
return "", fmt.Errorf("fetching release: %w", err)
|
|
||||||
}
|
|
||||||
defer resp.Body.Close() //nolint:errcheck
|
|
||||||
|
|
||||||
if resp.StatusCode != http.StatusOK {
|
|
||||||
return "", fmt.Errorf("unexpected status %s", resp.Status)
|
|
||||||
}
|
|
||||||
|
|
||||||
var release githubRelease
|
|
||||||
if err := json.NewDecoder(resp.Body).Decode(&release); err != nil {
|
|
||||||
return "", fmt.Errorf("decoding response: %w", err)
|
|
||||||
}
|
|
||||||
|
|
||||||
return release.TagName, nil
|
|
||||||
}
|
|
||||||
|
|
||||||
func removeDirectories(dirs []string) error {
|
|
||||||
var wg sync.WaitGroup
|
|
||||||
errCh := make(chan error, len(dirs))
|
|
||||||
|
|
||||||
for _, path := range dirs {
|
|
||||||
wg.Go(func() {
|
|
||||||
if err := os.RemoveAll(path); err != nil {
|
|
||||||
errCh <- fmt.Errorf("remove directory %s: %w", path, err)
|
|
||||||
}
|
|
||||||
})
|
|
||||||
}
|
|
||||||
|
|
||||||
wg.Wait()
|
|
||||||
close(errCh)
|
|
||||||
|
|
||||||
var errs []error
|
|
||||||
for err := range errCh {
|
|
||||||
errs = append(errs, err)
|
|
||||||
}
|
|
||||||
|
|
||||||
return errors.Join(errs...)
|
|
||||||
}
|
|
||||||
|
|
||||||
func createDirectories(dirs []string) error {
|
|
||||||
var wg sync.WaitGroup
|
|
||||||
errCh := make(chan error, len(dirs))
|
|
||||||
|
|
||||||
for _, path := range dirs {
|
|
||||||
wg.Go(func() {
|
|
||||||
if err := os.MkdirAll(path, 0755); err != nil {
|
|
||||||
errCh <- fmt.Errorf("create directory %s: %w", path, err)
|
|
||||||
}
|
|
||||||
})
|
|
||||||
}
|
|
||||||
|
|
||||||
wg.Wait()
|
|
||||||
close(errCh)
|
|
||||||
|
|
||||||
var errs []error
|
|
||||||
for err := range errCh {
|
|
||||||
errs = append(errs, err)
|
|
||||||
}
|
|
||||||
|
|
||||||
return errors.Join(errs...)
|
|
||||||
}
|
}
|
||||||
|
|
||||||
func download(files map[string]string) error {
|
func download(files map[string]string) error {
|
||||||
@@ -288,15 +71,15 @@ func download(files map[string]string) error {
|
|||||||
return errors.Join(errs...)
|
return errors.Join(errs...)
|
||||||
}
|
}
|
||||||
|
|
||||||
func downloadFile(rawURL, dest string) error {
|
func downloadFile(url, dest string) error {
|
||||||
resp, err := http.Get(rawURL) //nolint:gosec,noctx // static URLs, simple tool
|
resp, err := http.Get(url) //nolint:gosec,noctx // static URLs, simple tool
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return fmt.Errorf("GET %s: %w", rawURL, err)
|
return fmt.Errorf("GET %s: %w", url, err)
|
||||||
}
|
}
|
||||||
defer resp.Body.Close() //nolint:errcheck
|
defer resp.Body.Close() //nolint:errcheck
|
||||||
|
|
||||||
if resp.StatusCode != http.StatusOK {
|
if resp.StatusCode != http.StatusOK {
|
||||||
return fmt.Errorf("GET %s: status %s", rawURL, resp.Status)
|
return fmt.Errorf("GET %s: status %s", url, resp.Status)
|
||||||
}
|
}
|
||||||
|
|
||||||
out, err := os.Create(dest) //nolint:gosec // paths are hardcoded constants
|
out, err := os.Create(dest) //nolint:gosec // paths are hardcoded constants
|
||||||
|
|||||||
@@ -5,8 +5,6 @@ services:
|
|||||||
args:
|
args:
|
||||||
VERSION: ${VERSION:-dev}
|
VERSION: ${VERSION:-dev}
|
||||||
COMMIT: ${COMMIT:-unknown}
|
COMMIT: ${COMMIT:-unknown}
|
||||||
secrets:
|
|
||||||
- vendor_token
|
|
||||||
container_name: games
|
container_name: games
|
||||||
restart: unless-stopped
|
restart: unless-stopped
|
||||||
ports:
|
ports:
|
||||||
@@ -18,7 +16,3 @@ services:
|
|||||||
- PORT=8080
|
- PORT=8080
|
||||||
volumes:
|
volumes:
|
||||||
- ./data:/data
|
- ./data:/data
|
||||||
|
|
||||||
secrets:
|
|
||||||
vendor_token:
|
|
||||||
environment: VENDOR_TOKEN
|
|
||||||
|
|||||||
@@ -3,10 +3,10 @@ package auth
|
|||||||
import (
|
import (
|
||||||
"database/sql"
|
"database/sql"
|
||||||
"net/http"
|
"net/http"
|
||||||
"net/url"
|
|
||||||
|
|
||||||
"github.com/alexedwards/scs/v2"
|
"github.com/alexedwards/scs/v2"
|
||||||
"github.com/google/uuid"
|
"github.com/google/uuid"
|
||||||
|
"github.com/starfederation/datastar-go/datastar"
|
||||||
|
|
||||||
"github.com/ryanhamamura/games/auth"
|
"github.com/ryanhamamura/games/auth"
|
||||||
"github.com/ryanhamamura/games/db/repository"
|
"github.com/ryanhamamura/games/db/repository"
|
||||||
@@ -14,15 +14,20 @@ import (
|
|||||||
appsessions "github.com/ryanhamamura/games/sessions"
|
appsessions "github.com/ryanhamamura/games/sessions"
|
||||||
)
|
)
|
||||||
|
|
||||||
func HandleLoginPage(sessions *scs.SessionManager) http.HandlerFunc {
|
type LoginSignals struct {
|
||||||
return func(w http.ResponseWriter, r *http.Request) {
|
Username string `json:"username"`
|
||||||
// Capture return_url so we can redirect back after login
|
Password string `json:"password"` //nolint:gosec // form input, not stored
|
||||||
if returnURL := r.URL.Query().Get("return_url"); returnURL != "" {
|
|
||||||
sessions.Put(r.Context(), "return_url", returnURL)
|
|
||||||
}
|
}
|
||||||
|
|
||||||
errorMsg := r.URL.Query().Get("error")
|
type RegisterSignals struct {
|
||||||
if err := pages.LoginPage(errorMsg).Render(r.Context(), w); err != nil {
|
Username string `json:"username"`
|
||||||
|
Password string `json:"password"` //nolint:gosec // form input, not stored
|
||||||
|
Confirm string `json:"confirm"`
|
||||||
|
}
|
||||||
|
|
||||||
|
func HandleLoginPage() http.HandlerFunc {
|
||||||
|
return func(w http.ResponseWriter, r *http.Request) {
|
||||||
|
if err := pages.LoginPage().Render(r.Context(), w); err != nil {
|
||||||
http.Error(w, http.StatusText(http.StatusInternalServerError), http.StatusInternalServerError)
|
http.Error(w, http.StatusText(http.StatusInternalServerError), http.StatusInternalServerError)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -30,8 +35,7 @@ func HandleLoginPage(sessions *scs.SessionManager) http.HandlerFunc {
|
|||||||
|
|
||||||
func HandleRegisterPage() http.HandlerFunc {
|
func HandleRegisterPage() http.HandlerFunc {
|
||||||
return func(w http.ResponseWriter, r *http.Request) {
|
return func(w http.ResponseWriter, r *http.Request) {
|
||||||
errorMsg := r.URL.Query().Get("error")
|
if err := pages.RegisterPage().Render(r.Context(), w); err != nil {
|
||||||
if err := pages.RegisterPage(errorMsg).Render(r.Context(), w); err != nil {
|
|
||||||
http.Error(w, http.StatusText(http.StatusInternalServerError), http.StatusInternalServerError)
|
http.Error(w, http.StatusText(http.StatusInternalServerError), http.StatusInternalServerError)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -39,21 +43,25 @@ func HandleRegisterPage() http.HandlerFunc {
|
|||||||
|
|
||||||
func HandleLogin(queries *repository.Queries, sessions *scs.SessionManager) http.HandlerFunc {
|
func HandleLogin(queries *repository.Queries, sessions *scs.SessionManager) http.HandlerFunc {
|
||||||
return func(w http.ResponseWriter, r *http.Request) {
|
return func(w http.ResponseWriter, r *http.Request) {
|
||||||
r.Body = http.MaxBytesReader(w, r.Body, 1024)
|
var signals LoginSignals
|
||||||
username := r.FormValue("username")
|
if err := datastar.ReadSignals(r, &signals); err != nil {
|
||||||
password := r.FormValue("password")
|
http.Error(w, err.Error(), http.StatusBadRequest)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
user, err := queries.GetUserByUsername(r.Context(), username)
|
sse := datastar.NewSSE(w, r)
|
||||||
|
|
||||||
|
user, err := queries.GetUserByUsername(r.Context(), signals.Username)
|
||||||
if err == sql.ErrNoRows {
|
if err == sql.ErrNoRows {
|
||||||
http.Redirect(w, r, "/login?error="+url.QueryEscape("Invalid username or password"), http.StatusSeeOther)
|
sse.MarshalAndPatchSignals(map[string]any{"error": "Invalid username or password"}) //nolint:errcheck
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
if err != nil {
|
if err != nil {
|
||||||
http.Redirect(w, r, "/login?error="+url.QueryEscape("An error occurred"), http.StatusSeeOther)
|
sse.MarshalAndPatchSignals(map[string]any{"error": "An error occurred"}) //nolint:errcheck
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
if !auth.CheckPassword(password, user.PasswordHash) {
|
if !auth.CheckPassword(signals.Password, user.PasswordHash) {
|
||||||
http.Redirect(w, r, "/login?error="+url.QueryEscape("Invalid username or password"), http.StatusSeeOther)
|
sse.MarshalAndPatchSignals(map[string]any{"error": "Invalid username or password"}) //nolint:errcheck
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -68,43 +76,46 @@ func HandleLogin(queries *repository.Queries, sessions *scs.SessionManager) http
|
|||||||
redirectURL = returnURL
|
redirectURL = returnURL
|
||||||
}
|
}
|
||||||
|
|
||||||
http.Redirect(w, r, redirectURL, http.StatusSeeOther)
|
sse.Redirect(redirectURL) //nolint:errcheck
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
func HandleRegister(queries *repository.Queries, sessions *scs.SessionManager) http.HandlerFunc {
|
func HandleRegister(queries *repository.Queries, sessions *scs.SessionManager) http.HandlerFunc {
|
||||||
return func(w http.ResponseWriter, r *http.Request) {
|
return func(w http.ResponseWriter, r *http.Request) {
|
||||||
r.Body = http.MaxBytesReader(w, r.Body, 1024)
|
var signals RegisterSignals
|
||||||
username := r.FormValue("username")
|
if err := datastar.ReadSignals(r, &signals); err != nil {
|
||||||
password := r.FormValue("password")
|
http.Error(w, err.Error(), http.StatusBadRequest)
|
||||||
confirm := r.FormValue("confirm")
|
|
||||||
|
|
||||||
if err := auth.ValidateUsername(username); err != nil {
|
|
||||||
http.Redirect(w, r, "/register?error="+url.QueryEscape(err.Error()), http.StatusSeeOther)
|
|
||||||
return
|
|
||||||
}
|
|
||||||
if err := auth.ValidatePassword(password); err != nil {
|
|
||||||
http.Redirect(w, r, "/register?error="+url.QueryEscape(err.Error()), http.StatusSeeOther)
|
|
||||||
return
|
|
||||||
}
|
|
||||||
if password != confirm {
|
|
||||||
http.Redirect(w, r, "/register?error="+url.QueryEscape("Passwords do not match"), http.StatusSeeOther)
|
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
hash, err := auth.HashPassword(password)
|
sse := datastar.NewSSE(w, r)
|
||||||
|
|
||||||
|
if err := auth.ValidateUsername(signals.Username); err != nil {
|
||||||
|
sse.MarshalAndPatchSignals(map[string]any{"error": err.Error()}) //nolint:errcheck
|
||||||
|
return
|
||||||
|
}
|
||||||
|
if err := auth.ValidatePassword(signals.Password); err != nil {
|
||||||
|
sse.MarshalAndPatchSignals(map[string]any{"error": err.Error()}) //nolint:errcheck
|
||||||
|
return
|
||||||
|
}
|
||||||
|
if signals.Password != signals.Confirm {
|
||||||
|
sse.MarshalAndPatchSignals(map[string]any{"error": "Passwords do not match"}) //nolint:errcheck
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
hash, err := auth.HashPassword(signals.Password)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
http.Redirect(w, r, "/register?error="+url.QueryEscape("An error occurred"), http.StatusSeeOther)
|
sse.MarshalAndPatchSignals(map[string]any{"error": "An error occurred"}) //nolint:errcheck
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
user, err := queries.CreateUser(r.Context(), repository.CreateUserParams{
|
user, err := queries.CreateUser(r.Context(), repository.CreateUserParams{
|
||||||
ID: uuid.New().String(),
|
ID: uuid.New().String(),
|
||||||
Username: username,
|
Username: signals.Username,
|
||||||
PasswordHash: hash,
|
PasswordHash: hash,
|
||||||
})
|
})
|
||||||
if err != nil {
|
if err != nil {
|
||||||
http.Redirect(w, r, "/register?error="+url.QueryEscape("Username already taken"), http.StatusSeeOther)
|
sse.MarshalAndPatchSignals(map[string]any{"error": "Username already taken"}) //nolint:errcheck
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -119,6 +130,6 @@ func HandleRegister(queries *repository.Queries, sessions *scs.SessionManager) h
|
|||||||
redirectURL = returnURL
|
redirectURL = returnURL
|
||||||
}
|
}
|
||||||
|
|
||||||
http.Redirect(w, r, redirectURL, http.StatusSeeOther)
|
sse.Redirect(redirectURL) //nolint:errcheck
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,351 +0,0 @@
|
|||||||
package auth_test
|
|
||||||
|
|
||||||
import (
|
|
||||||
"context"
|
|
||||||
"database/sql"
|
|
||||||
"net/http"
|
|
||||||
"net/http/httptest"
|
|
||||||
"net/url"
|
|
||||||
"strings"
|
|
||||||
"testing"
|
|
||||||
|
|
||||||
"github.com/alexedwards/scs/v2"
|
|
||||||
"github.com/google/uuid"
|
|
||||||
|
|
||||||
"github.com/ryanhamamura/games/auth"
|
|
||||||
"github.com/ryanhamamura/games/db/repository"
|
|
||||||
featauth "github.com/ryanhamamura/games/features/auth"
|
|
||||||
"github.com/ryanhamamura/games/features/lobby"
|
|
||||||
appsessions "github.com/ryanhamamura/games/sessions"
|
|
||||||
"github.com/ryanhamamura/games/testutil"
|
|
||||||
)
|
|
||||||
|
|
||||||
// sessionCookieName is the default SCS cookie name used in tests.
|
|
||||||
const sessionCookieName = "session"
|
|
||||||
|
|
||||||
type testSetup struct {
|
|
||||||
db *sql.DB
|
|
||||||
queries *repository.Queries
|
|
||||||
sm *scs.SessionManager
|
|
||||||
}
|
|
||||||
|
|
||||||
func (s *testSetup) ctx() context.Context {
|
|
||||||
return context.Background()
|
|
||||||
}
|
|
||||||
|
|
||||||
func newTestSetup(t *testing.T) *testSetup {
|
|
||||||
t.Helper()
|
|
||||||
db, queries := testutil.NewTestDB(t)
|
|
||||||
sm := testutil.NewTestSessionManager(t, db)
|
|
||||||
return &testSetup{db: db, queries: queries, sm: sm}
|
|
||||||
}
|
|
||||||
|
|
||||||
// createTestUser inserts a user into the test database and returns the user ID.
|
|
||||||
func createTestUser(t *testing.T, setup *testSetup, username, password string) string {
|
|
||||||
t.Helper()
|
|
||||||
hash, err := auth.HashPassword(password)
|
|
||||||
if err != nil {
|
|
||||||
t.Fatalf("hashing password: %v", err)
|
|
||||||
}
|
|
||||||
id := uuid.New().String()
|
|
||||||
_, err = setup.queries.CreateUser(setup.ctx(), repository.CreateUserParams{
|
|
||||||
ID: id,
|
|
||||||
Username: username,
|
|
||||||
PasswordHash: hash,
|
|
||||||
})
|
|
||||||
if err != nil {
|
|
||||||
t.Fatalf("creating test user: %v", err)
|
|
||||||
}
|
|
||||||
return id
|
|
||||||
}
|
|
||||||
|
|
||||||
// postForm sends a POST request with form-encoded body through the session middleware,
|
|
||||||
// forwarding any cookies from a previous response.
|
|
||||||
func postForm(handler http.Handler, path string, values url.Values, cookies []*http.Cookie) *httptest.ResponseRecorder {
|
|
||||||
body := strings.NewReader(values.Encode())
|
|
||||||
req := httptest.NewRequest(http.MethodPost, path, body)
|
|
||||||
req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
|
|
||||||
for _, c := range cookies {
|
|
||||||
req.AddCookie(c)
|
|
||||||
}
|
|
||||||
rec := httptest.NewRecorder()
|
|
||||||
handler.ServeHTTP(rec, req)
|
|
||||||
return rec
|
|
||||||
}
|
|
||||||
|
|
||||||
// getPage sends a GET request through the session middleware, forwarding cookies.
|
|
||||||
func getPage(handler http.Handler, path string, cookies []*http.Cookie) *httptest.ResponseRecorder {
|
|
||||||
req := httptest.NewRequest(http.MethodGet, path, nil)
|
|
||||||
for _, c := range cookies {
|
|
||||||
req.AddCookie(c)
|
|
||||||
}
|
|
||||||
rec := httptest.NewRecorder()
|
|
||||||
handler.ServeHTTP(rec, req)
|
|
||||||
return rec
|
|
||||||
}
|
|
||||||
|
|
||||||
// extractSessionValue makes a GET request with the given cookies to a test endpoint
|
|
||||||
// that reads a session value, verifying the session was persisted correctly.
|
|
||||||
func extractSessionValue(t *testing.T, setup *testSetup, cookies []*http.Cookie, key string) string {
|
|
||||||
t.Helper()
|
|
||||||
var value string
|
|
||||||
handler := setup.sm.LoadAndSave(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
|
||||||
value = setup.sm.GetString(r.Context(), key)
|
|
||||||
}))
|
|
||||||
req := httptest.NewRequest(http.MethodGet, "/check-session", nil)
|
|
||||||
for _, c := range cookies {
|
|
||||||
req.AddCookie(c)
|
|
||||||
}
|
|
||||||
rec := httptest.NewRecorder()
|
|
||||||
handler.ServeHTTP(rec, req)
|
|
||||||
if rec.Code != http.StatusOK {
|
|
||||||
t.Fatalf("session check returned %d", rec.Code)
|
|
||||||
}
|
|
||||||
return value
|
|
||||||
}
|
|
||||||
|
|
||||||
func TestHandleLogin_Success(t *testing.T) {
|
|
||||||
setup := newTestSetup(t)
|
|
||||||
createTestUser(t, setup, "alice", "password123")
|
|
||||||
|
|
||||||
handler := setup.sm.LoadAndSave(featauth.HandleLogin(setup.queries, setup.sm))
|
|
||||||
rec := postForm(handler, "/auth/login", url.Values{
|
|
||||||
"username": {"alice"},
|
|
||||||
"password": {"password123"},
|
|
||||||
}, nil)
|
|
||||||
|
|
||||||
if rec.Code != http.StatusSeeOther {
|
|
||||||
t.Errorf("expected status %d, got %d", http.StatusSeeOther, rec.Code)
|
|
||||||
}
|
|
||||||
if loc := rec.Header().Get("Location"); loc != "/" {
|
|
||||||
t.Errorf("expected redirect to /, got %q", loc)
|
|
||||||
}
|
|
||||||
|
|
||||||
// Verify the response sets a session cookie
|
|
||||||
cookies := rec.Result().Cookies()
|
|
||||||
if !hasCookie(cookies, sessionCookieName) {
|
|
||||||
t.Fatal("response did not set a session cookie")
|
|
||||||
}
|
|
||||||
|
|
||||||
// Verify session contains user data by reading it back
|
|
||||||
userID := extractSessionValue(t, setup, cookies, appsessions.KeyUserID)
|
|
||||||
if userID == "" {
|
|
||||||
t.Error("session does not contain user_id after login")
|
|
||||||
}
|
|
||||||
nickname := extractSessionValue(t, setup, cookies, appsessions.KeyNickname)
|
|
||||||
if nickname != "alice" {
|
|
||||||
t.Errorf("expected nickname %q, got %q", "alice", nickname)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func TestHandleLogin_InvalidPassword(t *testing.T) {
|
|
||||||
setup := newTestSetup(t)
|
|
||||||
createTestUser(t, setup, "alice", "password123")
|
|
||||||
|
|
||||||
handler := setup.sm.LoadAndSave(featauth.HandleLogin(setup.queries, setup.sm))
|
|
||||||
rec := postForm(handler, "/auth/login", url.Values{
|
|
||||||
"username": {"alice"},
|
|
||||||
"password": {"wrongpassword"},
|
|
||||||
}, nil)
|
|
||||||
|
|
||||||
if rec.Code != http.StatusSeeOther {
|
|
||||||
t.Errorf("expected status %d, got %d", http.StatusSeeOther, rec.Code)
|
|
||||||
}
|
|
||||||
loc := rec.Header().Get("Location")
|
|
||||||
if !strings.HasPrefix(loc, "/login?error=") {
|
|
||||||
t.Errorf("expected redirect to /login?error=..., got %q", loc)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func TestHandleLogin_UnknownUser(t *testing.T) {
|
|
||||||
setup := newTestSetup(t)
|
|
||||||
|
|
||||||
handler := setup.sm.LoadAndSave(featauth.HandleLogin(setup.queries, setup.sm))
|
|
||||||
rec := postForm(handler, "/auth/login", url.Values{
|
|
||||||
"username": {"nonexistent"},
|
|
||||||
"password": {"password123"},
|
|
||||||
}, nil)
|
|
||||||
|
|
||||||
if rec.Code != http.StatusSeeOther {
|
|
||||||
t.Errorf("expected status %d, got %d", http.StatusSeeOther, rec.Code)
|
|
||||||
}
|
|
||||||
loc := rec.Header().Get("Location")
|
|
||||||
if !strings.HasPrefix(loc, "/login?error=") {
|
|
||||||
t.Errorf("expected redirect to /login?error=..., got %q", loc)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func TestHandleLogin_ReturnURL(t *testing.T) {
|
|
||||||
setup := newTestSetup(t)
|
|
||||||
createTestUser(t, setup, "alice", "password123")
|
|
||||||
|
|
||||||
// First, visit the login page with a return_url to store it in the session
|
|
||||||
loginPageHandler := setup.sm.LoadAndSave(featauth.HandleLoginPage(setup.sm))
|
|
||||||
pageRec := getPage(loginPageHandler, "/login?return_url=/games/abc", nil)
|
|
||||||
cookies := pageRec.Result().Cookies()
|
|
||||||
|
|
||||||
// Now log in with those cookies so the handler can read return_url from session
|
|
||||||
loginHandler := setup.sm.LoadAndSave(featauth.HandleLogin(setup.queries, setup.sm))
|
|
||||||
rec := postForm(loginHandler, "/auth/login", url.Values{
|
|
||||||
"username": {"alice"},
|
|
||||||
"password": {"password123"},
|
|
||||||
}, cookies)
|
|
||||||
|
|
||||||
if rec.Code != http.StatusSeeOther {
|
|
||||||
t.Errorf("expected status %d, got %d", http.StatusSeeOther, rec.Code)
|
|
||||||
}
|
|
||||||
if loc := rec.Header().Get("Location"); loc != "/games/abc" {
|
|
||||||
t.Errorf("expected redirect to /games/abc, got %q", loc)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func TestHandleRegister_Success(t *testing.T) {
|
|
||||||
setup := newTestSetup(t)
|
|
||||||
|
|
||||||
handler := setup.sm.LoadAndSave(featauth.HandleRegister(setup.queries, setup.sm))
|
|
||||||
rec := postForm(handler, "/auth/register", url.Values{
|
|
||||||
"username": {"newuser"},
|
|
||||||
"password": {"password123"},
|
|
||||||
"confirm": {"password123"},
|
|
||||||
}, nil)
|
|
||||||
|
|
||||||
if rec.Code != http.StatusSeeOther {
|
|
||||||
t.Errorf("expected status %d, got %d", http.StatusSeeOther, rec.Code)
|
|
||||||
}
|
|
||||||
if loc := rec.Header().Get("Location"); loc != "/" {
|
|
||||||
t.Errorf("expected redirect to /, got %q", loc)
|
|
||||||
}
|
|
||||||
|
|
||||||
cookies := rec.Result().Cookies()
|
|
||||||
if !hasCookie(cookies, sessionCookieName) {
|
|
||||||
t.Fatal("response did not set a session cookie")
|
|
||||||
}
|
|
||||||
|
|
||||||
userID := extractSessionValue(t, setup, cookies, appsessions.KeyUserID)
|
|
||||||
if userID == "" {
|
|
||||||
t.Error("session does not contain user_id after registration")
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func TestHandleRegister_PasswordMismatch(t *testing.T) {
|
|
||||||
setup := newTestSetup(t)
|
|
||||||
|
|
||||||
handler := setup.sm.LoadAndSave(featauth.HandleRegister(setup.queries, setup.sm))
|
|
||||||
rec := postForm(handler, "/auth/register", url.Values{
|
|
||||||
"username": {"newuser"},
|
|
||||||
"password": {"password123"},
|
|
||||||
"confirm": {"differentpassword"},
|
|
||||||
}, nil)
|
|
||||||
|
|
||||||
if rec.Code != http.StatusSeeOther {
|
|
||||||
t.Errorf("expected status %d, got %d", http.StatusSeeOther, rec.Code)
|
|
||||||
}
|
|
||||||
loc := rec.Header().Get("Location")
|
|
||||||
if !strings.Contains(loc, "Passwords+do+not+match") {
|
|
||||||
t.Errorf("expected error about password mismatch, got %q", loc)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func TestHandleRegister_InvalidUsername(t *testing.T) {
|
|
||||||
setup := newTestSetup(t)
|
|
||||||
|
|
||||||
handler := setup.sm.LoadAndSave(featauth.HandleRegister(setup.queries, setup.sm))
|
|
||||||
rec := postForm(handler, "/auth/register", url.Values{
|
|
||||||
"username": {"ab"}, // too short
|
|
||||||
"password": {"password123"},
|
|
||||||
"confirm": {"password123"},
|
|
||||||
}, nil)
|
|
||||||
|
|
||||||
if rec.Code != http.StatusSeeOther {
|
|
||||||
t.Errorf("expected status %d, got %d", http.StatusSeeOther, rec.Code)
|
|
||||||
}
|
|
||||||
loc := rec.Header().Get("Location")
|
|
||||||
if !strings.HasPrefix(loc, "/register?error=") {
|
|
||||||
t.Errorf("expected redirect to /register?error=..., got %q", loc)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func TestHandleRegister_ShortPassword(t *testing.T) {
|
|
||||||
setup := newTestSetup(t)
|
|
||||||
|
|
||||||
handler := setup.sm.LoadAndSave(featauth.HandleRegister(setup.queries, setup.sm))
|
|
||||||
rec := postForm(handler, "/auth/register", url.Values{
|
|
||||||
"username": {"validuser"},
|
|
||||||
"password": {"short"},
|
|
||||||
"confirm": {"short"},
|
|
||||||
}, nil)
|
|
||||||
|
|
||||||
if rec.Code != http.StatusSeeOther {
|
|
||||||
t.Errorf("expected status %d, got %d", http.StatusSeeOther, rec.Code)
|
|
||||||
}
|
|
||||||
loc := rec.Header().Get("Location")
|
|
||||||
if !strings.HasPrefix(loc, "/register?error=") {
|
|
||||||
t.Errorf("expected redirect to /register?error=..., got %q", loc)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func TestHandleRegister_DuplicateUsername(t *testing.T) {
|
|
||||||
setup := newTestSetup(t)
|
|
||||||
createTestUser(t, setup, "taken", "password123")
|
|
||||||
|
|
||||||
handler := setup.sm.LoadAndSave(featauth.HandleRegister(setup.queries, setup.sm))
|
|
||||||
rec := postForm(handler, "/auth/register", url.Values{
|
|
||||||
"username": {"taken"},
|
|
||||||
"password": {"password123"},
|
|
||||||
"confirm": {"password123"},
|
|
||||||
}, nil)
|
|
||||||
|
|
||||||
if rec.Code != http.StatusSeeOther {
|
|
||||||
t.Errorf("expected status %d, got %d", http.StatusSeeOther, rec.Code)
|
|
||||||
}
|
|
||||||
loc := rec.Header().Get("Location")
|
|
||||||
if !strings.Contains(loc, "Username+already+taken") {
|
|
||||||
t.Errorf("expected error about duplicate username, got %q", loc)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func TestHandleLogout(t *testing.T) {
|
|
||||||
setup := newTestSetup(t)
|
|
||||||
createTestUser(t, setup, "alice", "password123")
|
|
||||||
|
|
||||||
// Log in first to establish a session
|
|
||||||
loginHandler := setup.sm.LoadAndSave(featauth.HandleLogin(setup.queries, setup.sm))
|
|
||||||
loginRec := postForm(loginHandler, "/auth/login", url.Values{
|
|
||||||
"username": {"alice"},
|
|
||||||
"password": {"password123"},
|
|
||||||
}, nil)
|
|
||||||
cookies := loginRec.Result().Cookies()
|
|
||||||
|
|
||||||
// Verify we're logged in
|
|
||||||
userID := extractSessionValue(t, setup, cookies, appsessions.KeyUserID)
|
|
||||||
if userID == "" {
|
|
||||||
t.Fatal("expected to be logged in before testing logout")
|
|
||||||
}
|
|
||||||
|
|
||||||
// Now log out
|
|
||||||
logoutHandler := setup.sm.LoadAndSave(lobby.HandleLogout(setup.sm))
|
|
||||||
logoutRec := postForm(logoutHandler, "/logout", nil, cookies)
|
|
||||||
|
|
||||||
if logoutRec.Code != http.StatusSeeOther {
|
|
||||||
t.Errorf("expected status %d, got %d", http.StatusSeeOther, logoutRec.Code)
|
|
||||||
}
|
|
||||||
if loc := logoutRec.Header().Get("Location"); loc != "/" {
|
|
||||||
t.Errorf("expected redirect to /, got %q", loc)
|
|
||||||
}
|
|
||||||
|
|
||||||
// Verify session is cleared — use the cookies from the logout response
|
|
||||||
logoutCookies := logoutRec.Result().Cookies()
|
|
||||||
userID = extractSessionValue(t, setup, logoutCookies, appsessions.KeyUserID)
|
|
||||||
if userID != "" {
|
|
||||||
t.Errorf("expected empty user_id after logout, got %q", userID)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func hasCookie(cookies []*http.Cookie, name string) bool {
|
|
||||||
for _, c := range cookies {
|
|
||||||
if c.Name == name {
|
|
||||||
return true
|
|
||||||
}
|
|
||||||
}
|
|
||||||
return false
|
|
||||||
}
|
|
||||||
@@ -1,39 +1,45 @@
|
|||||||
package pages
|
package pages
|
||||||
|
|
||||||
import "github.com/ryanhamamura/games/features/common/layouts"
|
import (
|
||||||
|
"github.com/ryanhamamura/games/features/common/layouts"
|
||||||
|
"github.com/starfederation/datastar-go/datastar"
|
||||||
|
)
|
||||||
|
|
||||||
templ LoginPage(errorMsg string) {
|
templ LoginPage() {
|
||||||
@layouts.Base("Login") {
|
@layouts.Base("Login") {
|
||||||
<main class="max-w-sm mx-auto mt-8 text-center">
|
<main class="max-w-sm mx-auto mt-8 text-center" data-signals="{username: '', password: '', error: ''}">
|
||||||
<h1 class="text-3xl font-bold">Login</h1>
|
<h1 class="text-3xl font-bold">Login</h1>
|
||||||
<p class="mb-4">Sign in to your account</p>
|
<p class="mb-4">Sign in to your account</p>
|
||||||
if errorMsg != "" {
|
<div data-show="$error != ''" class="alert alert-error mb-4" data-text="$error"></div>
|
||||||
<div class="alert alert-error mb-4">{ errorMsg }</div>
|
<div>
|
||||||
}
|
|
||||||
<form method="POST" action="/auth/login">
|
|
||||||
<fieldset class="fieldset">
|
<fieldset class="fieldset">
|
||||||
<label class="label" for="username">Username</label>
|
<label class="label" for="username">Username</label>
|
||||||
<input
|
<input
|
||||||
class="input input-bordered w-full"
|
class="input input-bordered w-full"
|
||||||
id="username"
|
id="username"
|
||||||
name="username"
|
|
||||||
type="text"
|
type="text"
|
||||||
placeholder="Enter your username"
|
placeholder="Enter your username"
|
||||||
|
data-bind="username"
|
||||||
|
data-on:keydown={ "evt.key === 'Enter' && " + datastar.PostSSE("/auth/login") }
|
||||||
autofocus
|
autofocus
|
||||||
/>
|
/>
|
||||||
<label class="label" for="password">Password</label>
|
<label class="label" for="password">Password</label>
|
||||||
<input
|
<input
|
||||||
class="input input-bordered w-full"
|
class="input input-bordered w-full"
|
||||||
id="password"
|
id="password"
|
||||||
name="password"
|
|
||||||
type="password"
|
type="password"
|
||||||
placeholder="Enter your password"
|
placeholder="Enter your password"
|
||||||
|
data-bind="password"
|
||||||
|
data-on:keydown={ "evt.key === 'Enter' && " + datastar.PostSSE("/auth/login") }
|
||||||
/>
|
/>
|
||||||
</fieldset>
|
</fieldset>
|
||||||
<button type="submit" class="btn btn-primary w-full">
|
<button
|
||||||
|
class="btn btn-primary w-full"
|
||||||
|
data-on:click={ datastar.PostSSE("/auth/login") }
|
||||||
|
>
|
||||||
Login
|
Login
|
||||||
</button>
|
</button>
|
||||||
</form>
|
</div>
|
||||||
<p>
|
<p>
|
||||||
Don't have an account? <a class="link" href="/register">Register</a>
|
Don't have an account? <a class="link" href="/register">Register</a>
|
||||||
</p>
|
</p>
|
||||||
|
|||||||
@@ -1,47 +1,54 @@
|
|||||||
package pages
|
package pages
|
||||||
|
|
||||||
import "github.com/ryanhamamura/games/features/common/layouts"
|
import (
|
||||||
|
"github.com/ryanhamamura/games/features/common/layouts"
|
||||||
|
"github.com/starfederation/datastar-go/datastar"
|
||||||
|
)
|
||||||
|
|
||||||
templ RegisterPage(errorMsg string) {
|
templ RegisterPage() {
|
||||||
@layouts.Base("Register") {
|
@layouts.Base("Register") {
|
||||||
<main class="max-w-sm mx-auto mt-8 text-center">
|
<main class="max-w-sm mx-auto mt-8 text-center" data-signals="{username: '', password: '', confirm: '', error: ''}">
|
||||||
<h1 class="text-3xl font-bold">Register</h1>
|
<h1 class="text-3xl font-bold">Register</h1>
|
||||||
<p class="mb-4">Create a new account</p>
|
<p class="mb-4">Create a new account</p>
|
||||||
if errorMsg != "" {
|
<div data-show="$error != ''" class="alert alert-error mb-4" data-text="$error"></div>
|
||||||
<div class="alert alert-error mb-4">{ errorMsg }</div>
|
<div>
|
||||||
}
|
|
||||||
<form method="POST" action="/auth/register">
|
|
||||||
<fieldset class="fieldset">
|
<fieldset class="fieldset">
|
||||||
<label class="label" for="username">Username</label>
|
<label class="label" for="username">Username</label>
|
||||||
<input
|
<input
|
||||||
class="input input-bordered w-full"
|
class="input input-bordered w-full"
|
||||||
id="username"
|
id="username"
|
||||||
name="username"
|
|
||||||
type="text"
|
type="text"
|
||||||
placeholder="Choose a username"
|
placeholder="Choose a username"
|
||||||
|
data-bind="username"
|
||||||
|
data-on:keydown={ "evt.key === 'Enter' && " + datastar.PostSSE("/auth/register") }
|
||||||
autofocus
|
autofocus
|
||||||
/>
|
/>
|
||||||
<label class="label" for="password">Password</label>
|
<label class="label" for="password">Password</label>
|
||||||
<input
|
<input
|
||||||
class="input input-bordered w-full"
|
class="input input-bordered w-full"
|
||||||
id="password"
|
id="password"
|
||||||
name="password"
|
|
||||||
type="password"
|
type="password"
|
||||||
placeholder="Choose a password (min 8 chars)"
|
placeholder="Choose a password (min 8 chars)"
|
||||||
|
data-bind="password"
|
||||||
|
data-on:keydown={ "evt.key === 'Enter' && " + datastar.PostSSE("/auth/register") }
|
||||||
/>
|
/>
|
||||||
<label class="label" for="confirm">Confirm Password</label>
|
<label class="label" for="confirm">Confirm Password</label>
|
||||||
<input
|
<input
|
||||||
class="input input-bordered w-full"
|
class="input input-bordered w-full"
|
||||||
id="confirm"
|
id="confirm"
|
||||||
name="confirm"
|
|
||||||
type="password"
|
type="password"
|
||||||
placeholder="Confirm your password"
|
placeholder="Confirm your password"
|
||||||
|
data-bind="confirm"
|
||||||
|
data-on:keydown={ "evt.key === 'Enter' && " + datastar.PostSSE("/auth/register") }
|
||||||
/>
|
/>
|
||||||
</fieldset>
|
</fieldset>
|
||||||
<button type="submit" class="btn btn-primary w-full">
|
<button
|
||||||
|
class="btn btn-primary w-full"
|
||||||
|
data-on:click={ datastar.PostSSE("/auth/register") }
|
||||||
|
>
|
||||||
Register
|
Register
|
||||||
</button>
|
</button>
|
||||||
</form>
|
</div>
|
||||||
<p>
|
<p>
|
||||||
Already have an account? <a class="link" href="/login">Login</a>
|
Already have an account? <a class="link" href="/login">Login</a>
|
||||||
</p>
|
</p>
|
||||||
|
|||||||
@@ -9,7 +9,7 @@ import (
|
|||||||
)
|
)
|
||||||
|
|
||||||
func SetupRoutes(router chi.Router, queries *repository.Queries, sessions *scs.SessionManager) {
|
func SetupRoutes(router chi.Router, queries *repository.Queries, sessions *scs.SessionManager) {
|
||||||
router.Get("/login", HandleLoginPage(sessions))
|
router.Get("/login", HandleLoginPage())
|
||||||
router.Get("/register", HandleRegisterPage())
|
router.Get("/register", HandleRegisterPage())
|
||||||
router.Post("/auth/login", HandleLogin(queries, sessions))
|
router.Post("/auth/login", HandleLogin(queries, sessions))
|
||||||
router.Post("/auth/register", HandleRegister(queries, sessions))
|
router.Post("/auth/register", HandleRegister(queries, sessions))
|
||||||
|
|||||||
@@ -1,23 +1,46 @@
|
|||||||
package c4game
|
package c4game
|
||||||
|
|
||||||
import (
|
import (
|
||||||
|
"fmt"
|
||||||
"net/http"
|
"net/http"
|
||||||
"strconv"
|
"strconv"
|
||||||
"time"
|
"time"
|
||||||
|
|
||||||
"github.com/alexedwards/scs/v2"
|
"github.com/alexedwards/scs/v2"
|
||||||
"github.com/go-chi/chi/v5"
|
"github.com/go-chi/chi/v5"
|
||||||
|
"github.com/nats-io/nats.go"
|
||||||
"github.com/starfederation/datastar-go/datastar"
|
"github.com/starfederation/datastar-go/datastar"
|
||||||
|
|
||||||
"github.com/ryanhamamura/games/chat"
|
"github.com/ryanhamamura/games/chat"
|
||||||
chatcomponents "github.com/ryanhamamura/games/chat/components"
|
chatcomponents "github.com/ryanhamamura/games/chat/components"
|
||||||
"github.com/ryanhamamura/games/connect4"
|
"github.com/ryanhamamura/games/connect4"
|
||||||
|
"github.com/ryanhamamura/games/db/repository"
|
||||||
"github.com/ryanhamamura/games/features/c4game/pages"
|
"github.com/ryanhamamura/games/features/c4game/pages"
|
||||||
"github.com/ryanhamamura/games/features/c4game/services"
|
|
||||||
"github.com/ryanhamamura/games/sessions"
|
"github.com/ryanhamamura/games/sessions"
|
||||||
)
|
)
|
||||||
|
|
||||||
func HandleGamePage(store *connect4.Store, svc *services.GameService, sm *scs.SessionManager) http.HandlerFunc {
|
// c4ChatColors maps player color (1=Red, 2=Yellow) to CSS background colors.
|
||||||
|
var c4ChatColors = map[int]string{
|
||||||
|
0: "#4a2a3a", // color 1 stored as slot 0
|
||||||
|
1: "#2a4545", // color 2 stored as slot 1
|
||||||
|
}
|
||||||
|
|
||||||
|
func c4ChatColor(slot int) string {
|
||||||
|
if c, ok := c4ChatColors[slot]; ok {
|
||||||
|
return c
|
||||||
|
}
|
||||||
|
return "#666"
|
||||||
|
}
|
||||||
|
|
||||||
|
func c4ChatConfig(gameID string) chatcomponents.Config {
|
||||||
|
return chatcomponents.Config{
|
||||||
|
CSSPrefix: "c4",
|
||||||
|
PostURL: fmt.Sprintf("/games/%s/chat", gameID),
|
||||||
|
Color: c4ChatColor,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func HandleGamePage(store *connect4.Store, sm *scs.SessionManager, queries *repository.Queries) http.HandlerFunc {
|
||||||
return func(w http.ResponseWriter, r *http.Request) {
|
return func(w http.ResponseWriter, r *http.Request) {
|
||||||
gameID := chi.URLParam(r, "id")
|
gameID := chi.URLParam(r, "id")
|
||||||
|
|
||||||
@@ -61,17 +84,16 @@ func HandleGamePage(store *connect4.Store, svc *services.GameService, sm *scs.Se
|
|||||||
}
|
}
|
||||||
|
|
||||||
g := gi.GetGame()
|
g := gi.GetGame()
|
||||||
room := svc.ChatRoom(gameID)
|
room := chat.NewPersistentRoom(nil, "", queries, gameID)
|
||||||
|
|
||||||
if err := pages.GamePage(g, myColor, room.Messages(), svc.ChatConfig(gameID)).Render(r.Context(), w); err != nil {
|
if err := pages.GamePage(g, myColor, room.Messages(), c4ChatConfig(gameID)).Render(r.Context(), w); err != nil {
|
||||||
http.Error(w, http.StatusText(http.StatusInternalServerError), http.StatusInternalServerError)
|
http.Error(w, http.StatusText(http.StatusInternalServerError), http.StatusInternalServerError)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
func HandleGameEvents(store *connect4.Store, svc *services.GameService, sm *scs.SessionManager) http.HandlerFunc {
|
func HandleGameEvents(store *connect4.Store, nc *nats.Conn, sm *scs.SessionManager, queries *repository.Queries) http.HandlerFunc {
|
||||||
return func(w http.ResponseWriter, r *http.Request) {
|
return func(w http.ResponseWriter, r *http.Request) {
|
||||||
ctx := r.Context()
|
|
||||||
gameID := chi.URLParam(r, "id")
|
gameID := chi.URLParam(r, "id")
|
||||||
|
|
||||||
gi, exists := store.Get(gameID)
|
gi, exists := store.Get(gameID)
|
||||||
@@ -81,74 +103,72 @@ func HandleGameEvents(store *connect4.Store, svc *services.GameService, sm *scs.
|
|||||||
}
|
}
|
||||||
|
|
||||||
playerID := sessions.GetPlayerID(sm, r)
|
playerID := sessions.GetPlayerID(sm, r)
|
||||||
|
myColor := gi.GetPlayerColor(playerID)
|
||||||
|
|
||||||
// Subscribe to game state updates BEFORE creating SSE
|
|
||||||
gameSub, gameCh, err := svc.SubscribeGameUpdates(gameID)
|
|
||||||
if err != nil {
|
|
||||||
http.Error(w, err.Error(), http.StatusInternalServerError)
|
|
||||||
return
|
|
||||||
}
|
|
||||||
defer gameSub.Unsubscribe() //nolint:errcheck
|
|
||||||
|
|
||||||
// Subscribe to chat messages BEFORE creating SSE
|
|
||||||
chatCfg := svc.ChatConfig(gameID)
|
|
||||||
room := svc.ChatRoom(gameID)
|
|
||||||
chatCh, cleanupChat := room.Subscribe()
|
|
||||||
defer cleanupChat()
|
|
||||||
|
|
||||||
// Setup heartbeat BEFORE creating SSE
|
|
||||||
heartbeat := time.NewTicker(1 * time.Second)
|
|
||||||
defer heartbeat.Stop()
|
|
||||||
|
|
||||||
// NOW create SSE
|
|
||||||
sse := datastar.NewSSE(w, r, datastar.WithCompression(
|
sse := datastar.NewSSE(w, r, datastar.WithCompression(
|
||||||
datastar.WithBrotli(datastar.WithBrotliLevel(5)),
|
datastar.WithBrotli(datastar.WithBrotliLevel(5)),
|
||||||
))
|
))
|
||||||
|
|
||||||
// Define patch function
|
chatCfg := c4ChatConfig(gameID)
|
||||||
|
room := chat.NewPersistentRoom(nc, connect4.ChatSubject(gameID), queries, gameID)
|
||||||
|
|
||||||
patchAll := func() error {
|
patchAll := func() error {
|
||||||
myColor := gi.GetPlayerColor(playerID)
|
myColor = gi.GetPlayerColor(playerID)
|
||||||
g := gi.GetGame()
|
g := gi.GetGame()
|
||||||
return sse.PatchElementTempl(pages.GameContent(g, myColor, room.Messages(), chatCfg))
|
return sse.PatchElementTempl(pages.GameContent(g, myColor, room.Messages(), chatCfg))
|
||||||
}
|
}
|
||||||
|
|
||||||
// Send initial state
|
sendPing := func() error {
|
||||||
|
return sse.PatchSignals([]byte(fmt.Sprintf(`{"lastPing":%d}`, time.Now().UnixMilli())))
|
||||||
|
}
|
||||||
|
|
||||||
|
// Send initial render and ping
|
||||||
|
if err := sendPing(); err != nil {
|
||||||
|
return
|
||||||
|
}
|
||||||
if err := patchAll(); err != nil {
|
if err := patchAll(); err != nil {
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
// Event loop
|
heartbeat := time.NewTicker(15 * time.Second)
|
||||||
|
defer heartbeat.Stop()
|
||||||
|
|
||||||
|
// Subscribe to game state updates
|
||||||
|
gameCh := make(chan *nats.Msg, 64)
|
||||||
|
gameSub, err := nc.ChanSubscribe(connect4.GameSubject(gameID), gameCh)
|
||||||
|
if err != nil {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
defer gameSub.Unsubscribe() //nolint:errcheck
|
||||||
|
|
||||||
|
// Subscribe to chat messages
|
||||||
|
chatCh, chatSub, err := room.Subscribe()
|
||||||
|
if err != nil {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
defer chatSub.Unsubscribe() //nolint:errcheck
|
||||||
|
|
||||||
|
ctx := r.Context()
|
||||||
for {
|
for {
|
||||||
select {
|
select {
|
||||||
case <-ctx.Done():
|
case <-ctx.Done():
|
||||||
return
|
return
|
||||||
|
case <-heartbeat.C:
|
||||||
case <-gameCh:
|
if err := sendPing(); err != nil {
|
||||||
// Drain rapid-fire notifications
|
return
|
||||||
drainGame:
|
|
||||||
for {
|
|
||||||
select {
|
|
||||||
case <-gameCh:
|
|
||||||
default:
|
|
||||||
break drainGame
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
case <-gameCh:
|
||||||
if err := patchAll(); err != nil {
|
if err := patchAll(); err != nil {
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
case msg := <-chatCh:
|
||||||
case chatMsg := <-chatCh:
|
chatMsg, _ := room.Receive(msg.Data)
|
||||||
if err := sse.PatchElementTempl(
|
err := sse.PatchElementTempl(
|
||||||
chatcomponents.ChatMessage(chatMsg, chatCfg),
|
chatcomponents.ChatMessage(chatMsg, chatCfg),
|
||||||
datastar.WithSelectorID("c4-chat-history"),
|
datastar.WithSelectorID("c4-chat-history"),
|
||||||
datastar.WithModeAppend(),
|
datastar.WithModeAppend(),
|
||||||
); err != nil {
|
)
|
||||||
return
|
if err != nil {
|
||||||
}
|
|
||||||
|
|
||||||
case <-heartbeat.C:
|
|
||||||
// Heartbeat refreshes game state to keep connection alive
|
|
||||||
if err := patchAll(); err != nil {
|
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -185,7 +205,7 @@ func HandleDropPiece(store *connect4.Store, sm *scs.SessionManager) http.Handler
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
func HandleSendChat(store *connect4.Store, svc *services.GameService, sm *scs.SessionManager) http.HandlerFunc {
|
func HandleSendChat(store *connect4.Store, nc *nats.Conn, sm *scs.SessionManager, queries *repository.Queries) http.HandlerFunc {
|
||||||
return func(w http.ResponseWriter, r *http.Request) {
|
return func(w http.ResponseWriter, r *http.Request) {
|
||||||
gameID := chi.URLParam(r, "id")
|
gameID := chi.URLParam(r, "id")
|
||||||
|
|
||||||
@@ -232,7 +252,7 @@ func HandleSendChat(store *connect4.Store, svc *services.GameService, sm *scs.Se
|
|||||||
Message: signals.ChatMsg,
|
Message: signals.ChatMsg,
|
||||||
Time: time.Now().UnixMilli(),
|
Time: time.Now().UnixMilli(),
|
||||||
}
|
}
|
||||||
room := svc.ChatRoom(gameID)
|
room := chat.NewPersistentRoom(nc, connect4.ChatSubject(gameID), queries, gameID)
|
||||||
room.Send(msg)
|
room.Send(msg)
|
||||||
|
|
||||||
sse := datastar.NewSSE(w, r)
|
sse := datastar.NewSSE(w, r)
|
||||||
|
|||||||
@@ -15,17 +15,17 @@ templ GamePage(g *connect4.Game, myColor int, messages []chat.Message, chatCfg c
|
|||||||
@layouts.Base("Connect 4") {
|
@layouts.Base("Connect 4") {
|
||||||
<main
|
<main
|
||||||
class="flex flex-col items-center gap-4 p-4"
|
class="flex flex-col items-center gap-4 p-4"
|
||||||
data-signals="{chatMsg: ''}"
|
data-signals="{chatMsg: '', lastPing: 0}"
|
||||||
data-init={ fmt.Sprintf("@get('/games/%s/events',{requestCancellation:'disabled'})", g.ID) }
|
data-init={ fmt.Sprintf("@get('/games/%s/events',{requestCancellation:'disabled'})", g.ID) }
|
||||||
>
|
>
|
||||||
|
@sharedcomponents.ConnectionIndicator()
|
||||||
@GameContent(g, myColor, messages, chatCfg)
|
@GameContent(g, myColor, messages, chatCfg)
|
||||||
</main>
|
</main>
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
templ GameContent(g *connect4.Game, myColor int, messages []chat.Message, chatCfg chatcomponents.Config) {
|
templ GameContent(g *connect4.Game, myColor int, messages []chat.Message, chatCfg chatcomponents.Config) {
|
||||||
<div id="game-content" class="flex flex-col items-center gap-4">
|
<div id="game-content">
|
||||||
@sharedcomponents.LiveClock()
|
|
||||||
@sharedcomponents.BackToLobby()
|
@sharedcomponents.BackToLobby()
|
||||||
@sharedcomponents.StealthTitle("text-3xl font-bold")
|
@sharedcomponents.StealthTitle("text-3xl font-bold")
|
||||||
@components.PlayerInfo(g, myColor)
|
@components.PlayerInfo(g, myColor)
|
||||||
|
|||||||
@@ -4,22 +4,24 @@ package c4game
|
|||||||
import (
|
import (
|
||||||
"github.com/alexedwards/scs/v2"
|
"github.com/alexedwards/scs/v2"
|
||||||
"github.com/go-chi/chi/v5"
|
"github.com/go-chi/chi/v5"
|
||||||
|
"github.com/nats-io/nats.go"
|
||||||
|
|
||||||
"github.com/ryanhamamura/games/connect4"
|
"github.com/ryanhamamura/games/connect4"
|
||||||
"github.com/ryanhamamura/games/features/c4game/services"
|
"github.com/ryanhamamura/games/db/repository"
|
||||||
)
|
)
|
||||||
|
|
||||||
func SetupRoutes(
|
func SetupRoutes(
|
||||||
router chi.Router,
|
router chi.Router,
|
||||||
store *connect4.Store,
|
store *connect4.Store,
|
||||||
svc *services.GameService,
|
nc *nats.Conn,
|
||||||
sessions *scs.SessionManager,
|
sessions *scs.SessionManager,
|
||||||
|
queries *repository.Queries,
|
||||||
) {
|
) {
|
||||||
router.Route("/games/{id}", func(r chi.Router) {
|
router.Route("/games/{id}", func(r chi.Router) {
|
||||||
r.Get("/", HandleGamePage(store, svc, sessions))
|
r.Get("/", HandleGamePage(store, sessions, queries))
|
||||||
r.Get("/events", HandleGameEvents(store, svc, sessions))
|
r.Get("/events", HandleGameEvents(store, nc, sessions, queries))
|
||||||
r.Post("/drop", HandleDropPiece(store, sessions))
|
r.Post("/drop", HandleDropPiece(store, sessions))
|
||||||
r.Post("/chat", HandleSendChat(store, svc, sessions))
|
r.Post("/chat", HandleSendChat(store, nc, sessions, queries))
|
||||||
r.Post("/join", HandleSetNickname(store, sessions))
|
r.Post("/join", HandleSetNickname(store, sessions))
|
||||||
r.Post("/rematch", HandleRematch(store, sessions))
|
r.Post("/rematch", HandleRematch(store, sessions))
|
||||||
})
|
})
|
||||||
|
|||||||
@@ -1,70 +0,0 @@
|
|||||||
// Package services provides the game service layer for Connect 4,
|
|
||||||
// handling NATS subscriptions and chat room management.
|
|
||||||
package services
|
|
||||||
|
|
||||||
import (
|
|
||||||
"fmt"
|
|
||||||
|
|
||||||
"github.com/nats-io/nats.go"
|
|
||||||
|
|
||||||
"github.com/ryanhamamura/games/chat"
|
|
||||||
chatcomponents "github.com/ryanhamamura/games/chat/components"
|
|
||||||
"github.com/ryanhamamura/games/connect4"
|
|
||||||
"github.com/ryanhamamura/games/db/repository"
|
|
||||||
)
|
|
||||||
|
|
||||||
// c4ChatColors maps player slot (0-indexed) to CSS background colors.
|
|
||||||
var c4ChatColors = map[int]string{
|
|
||||||
0: "#4a2a3a", // Red player
|
|
||||||
1: "#2a4545", // Yellow player
|
|
||||||
}
|
|
||||||
|
|
||||||
func c4ChatColor(slot int) string {
|
|
||||||
if c, ok := c4ChatColors[slot]; ok {
|
|
||||||
return c
|
|
||||||
}
|
|
||||||
return "#666"
|
|
||||||
}
|
|
||||||
|
|
||||||
// GameService manages NATS subscriptions and chat for Connect 4 games.
|
|
||||||
type GameService struct {
|
|
||||||
nc *nats.Conn
|
|
||||||
queries *repository.Queries
|
|
||||||
}
|
|
||||||
|
|
||||||
// NewGameService creates a new game service.
|
|
||||||
func NewGameService(nc *nats.Conn, queries *repository.Queries) *GameService {
|
|
||||||
return &GameService{
|
|
||||||
nc: nc,
|
|
||||||
queries: queries,
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// SubscribeGameUpdates returns a NATS subscription and channel for game state updates.
|
|
||||||
func (s *GameService) SubscribeGameUpdates(gameID string) (*nats.Subscription, <-chan *nats.Msg, error) {
|
|
||||||
ch := make(chan *nats.Msg, 64)
|
|
||||||
sub, err := s.nc.ChanSubscribe(connect4.GameSubject(gameID), ch)
|
|
||||||
if err != nil {
|
|
||||||
return nil, nil, fmt.Errorf("subscribing to game updates: %w", err)
|
|
||||||
}
|
|
||||||
return sub, ch, nil
|
|
||||||
}
|
|
||||||
|
|
||||||
// ChatConfig returns the chat configuration for a game.
|
|
||||||
func (s *GameService) ChatConfig(gameID string) chatcomponents.Config {
|
|
||||||
return chatcomponents.Config{
|
|
||||||
CSSPrefix: "c4",
|
|
||||||
PostURL: fmt.Sprintf("/games/%s/chat", gameID),
|
|
||||||
Color: c4ChatColor,
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// ChatRoom returns a persistent chat room for a game.
|
|
||||||
func (s *GameService) ChatRoom(gameID string) *chat.Room {
|
|
||||||
return chat.NewPersistentRoom(s.nc, connect4.ChatSubject(gameID), s.queries, gameID)
|
|
||||||
}
|
|
||||||
|
|
||||||
// PublishGameUpdate sends a notification that the game state has changed.
|
|
||||||
func (s *GameService) PublishGameUpdate(gameID string) error {
|
|
||||||
return s.nc.Publish(connect4.GameSubject(gameID), nil)
|
|
||||||
}
|
|
||||||
@@ -1,10 +1,6 @@
|
|||||||
package components
|
package components
|
||||||
|
|
||||||
import (
|
import "github.com/starfederation/datastar-go/datastar"
|
||||||
"time"
|
|
||||||
|
|
||||||
"github.com/starfederation/datastar-go/datastar"
|
|
||||||
)
|
|
||||||
|
|
||||||
templ BackToLobby() {
|
templ BackToLobby() {
|
||||||
<a class="link text-sm opacity-70" href="/">← Back</a>
|
<a class="link text-sm opacity-70" href="/">← Back</a>
|
||||||
@@ -48,12 +44,18 @@ templ NicknamePrompt(returnPath string) {
|
|||||||
</main>
|
</main>
|
||||||
}
|
}
|
||||||
|
|
||||||
// LiveClock shows the current server time, updated every second via SSE.
|
// ConnectionIndicator shows a small dot indicating SSE connection status.
|
||||||
// If the clock stops updating, users know the connection is stale.
|
// It requires a `lastPing` signal (unix ms timestamp) to be set by the server.
|
||||||
templ LiveClock() {
|
templ ConnectionIndicator() {
|
||||||
<div class="fixed top-2 right-2 flex items-center gap-1.5 text-xs opacity-60 font-mono">
|
<div
|
||||||
<div style="width: 6px; height: 6px; border-radius: 50%; background-color: #22c55e;"></div>
|
id="connection-indicator"
|
||||||
{ time.Now().Format("15:04:05") }
|
class="fixed top-2 right-2 flex items-center gap-1 text-xs text-gray-500"
|
||||||
|
title="Connection status"
|
||||||
|
>
|
||||||
|
<span
|
||||||
|
class="w-2 h-2 rounded-full transition-colors duration-300"
|
||||||
|
data-class="{'bg-green-500': Date.now() - $lastPing < 20000, 'bg-red-500': Date.now() - $lastPing >= 20000}"
|
||||||
|
></span>
|
||||||
</div>
|
</div>
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -1,7 +1,6 @@
|
|||||||
package layouts
|
package layouts
|
||||||
|
|
||||||
import (
|
import (
|
||||||
"github.com/ryanhamamura/games/assets"
|
|
||||||
"github.com/ryanhamamura/games/config"
|
"github.com/ryanhamamura/games/config"
|
||||||
"github.com/ryanhamamura/games/version"
|
"github.com/ryanhamamura/games/version"
|
||||||
)
|
)
|
||||||
@@ -12,8 +11,8 @@ templ Base(title string) {
|
|||||||
<head>
|
<head>
|
||||||
<title>{ title }</title>
|
<title>{ title }</title>
|
||||||
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1, user-scalable=0"/>
|
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1, user-scalable=0"/>
|
||||||
<script defer type="module" src={ assets.StaticPath("js/datastar/datastar.js") }></script>
|
<script defer type="module" src="/assets/js/datastar.js"></script>
|
||||||
<link href={ assets.StaticPath("css/output.css") } rel="stylesheet" type="text/css"/>
|
<link href="/assets/css/output.css" rel="stylesheet" type="text/css"/>
|
||||||
</head>
|
</head>
|
||||||
<body class="flex flex-col h-screen">
|
<body class="flex flex-col h-screen">
|
||||||
if config.Global.Environment == config.Dev {
|
if config.Global.Environment == config.Dev {
|
||||||
|
|||||||
@@ -171,6 +171,7 @@ func HandleLogout(sessions *scs.SessionManager) http.HandlerFunc {
|
|||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
http.Redirect(w, r, "/", http.StatusSeeOther)
|
sse := datastar.NewSSE(w, r)
|
||||||
|
sse.ExecuteScript("window.location.href='/'") //nolint:errcheck
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -20,11 +20,13 @@ templ LobbyPage(data LobbyData) {
|
|||||||
if data.IsLoggedIn {
|
if data.IsLoggedIn {
|
||||||
<div class="flex justify-center items-center gap-4 mb-4 p-2 bg-base-200 rounded-lg">
|
<div class="flex justify-center items-center gap-4 mb-4 p-2 bg-base-200 rounded-lg">
|
||||||
<span>Logged in as <strong>{ data.Username }</strong></span>
|
<span>Logged in as <strong>{ data.Username }</strong></span>
|
||||||
<form method="POST" action="/logout" class="inline">
|
<button
|
||||||
<button type="submit" class="btn btn-ghost btn-sm">
|
type="button"
|
||||||
|
class="btn btn-ghost btn-sm"
|
||||||
|
data-on:click={ datastar.PostSSE("/logout") }
|
||||||
|
>
|
||||||
Logout
|
Logout
|
||||||
</button>
|
</button>
|
||||||
</form>
|
|
||||||
</div>
|
</div>
|
||||||
} else {
|
} else {
|
||||||
<div class="alert text-sm mb-4">
|
<div class="alert text-sm mb-4">
|
||||||
|
|||||||
@@ -1,24 +1,40 @@
|
|||||||
package snakegame
|
package snakegame
|
||||||
|
|
||||||
import (
|
import (
|
||||||
"errors"
|
"fmt"
|
||||||
"net/http"
|
"net/http"
|
||||||
"strconv"
|
"strconv"
|
||||||
"time"
|
"time"
|
||||||
|
|
||||||
"github.com/alexedwards/scs/v2"
|
"github.com/alexedwards/scs/v2"
|
||||||
"github.com/go-chi/chi/v5"
|
"github.com/go-chi/chi/v5"
|
||||||
|
"github.com/nats-io/nats.go"
|
||||||
"github.com/starfederation/datastar-go/datastar"
|
"github.com/starfederation/datastar-go/datastar"
|
||||||
|
|
||||||
"github.com/ryanhamamura/games/chat"
|
"github.com/ryanhamamura/games/chat"
|
||||||
chatcomponents "github.com/ryanhamamura/games/chat/components"
|
chatcomponents "github.com/ryanhamamura/games/chat/components"
|
||||||
"github.com/ryanhamamura/games/features/snakegame/pages"
|
"github.com/ryanhamamura/games/features/snakegame/pages"
|
||||||
"github.com/ryanhamamura/games/features/snakegame/services"
|
|
||||||
"github.com/ryanhamamura/games/sessions"
|
"github.com/ryanhamamura/games/sessions"
|
||||||
"github.com/ryanhamamura/games/snake"
|
"github.com/ryanhamamura/games/snake"
|
||||||
)
|
)
|
||||||
|
|
||||||
func HandleSnakePage(snakeStore *snake.SnakeStore, svc *services.GameService, sm *scs.SessionManager) http.HandlerFunc {
|
func snakeChatColor(slot int) string {
|
||||||
|
if slot >= 0 && slot < len(snake.SnakeColors) {
|
||||||
|
return snake.SnakeColors[slot]
|
||||||
|
}
|
||||||
|
return "#666"
|
||||||
|
}
|
||||||
|
|
||||||
|
func snakeChatConfig(gameID string) chatcomponents.Config {
|
||||||
|
return chatcomponents.Config{
|
||||||
|
CSSPrefix: "snake",
|
||||||
|
PostURL: fmt.Sprintf("/snake/%s/chat", gameID),
|
||||||
|
Color: snakeChatColor,
|
||||||
|
StopKeyPropagation: true,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func HandleSnakePage(snakeStore *snake.SnakeStore, sm *scs.SessionManager) http.HandlerFunc {
|
||||||
return func(w http.ResponseWriter, r *http.Request) {
|
return func(w http.ResponseWriter, r *http.Request) {
|
||||||
gameID := chi.URLParam(r, "id")
|
gameID := chi.URLParam(r, "id")
|
||||||
si, ok := snakeStore.Get(gameID)
|
si, ok := snakeStore.Get(gameID)
|
||||||
@@ -60,14 +76,13 @@ func HandleSnakePage(snakeStore *snake.SnakeStore, svc *services.GameService, sm
|
|||||||
}
|
}
|
||||||
|
|
||||||
sg := si.GetGame()
|
sg := si.GetGame()
|
||||||
chatCfg := svc.ChatConfig(gameID)
|
if err := pages.GamePage(sg, mySlot, nil, snakeChatConfig(gameID), gameID).Render(r.Context(), w); err != nil {
|
||||||
if err := pages.GamePage(sg, mySlot, nil, chatCfg, gameID).Render(r.Context(), w); err != nil {
|
|
||||||
http.Error(w, http.StatusText(http.StatusInternalServerError), http.StatusInternalServerError)
|
http.Error(w, http.StatusText(http.StatusInternalServerError), http.StatusInternalServerError)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
func HandleSnakeEvents(snakeStore *snake.SnakeStore, svc *services.GameService, sm *scs.SessionManager) http.HandlerFunc {
|
func HandleSnakeEvents(snakeStore *snake.SnakeStore, nc *nats.Conn, sm *scs.SessionManager) http.HandlerFunc {
|
||||||
return func(w http.ResponseWriter, r *http.Request) {
|
return func(w http.ResponseWriter, r *http.Request) {
|
||||||
gameID := chi.URLParam(r, "id")
|
gameID := chi.URLParam(r, "id")
|
||||||
si, ok := snakeStore.Get(gameID)
|
si, ok := snakeStore.Get(gameID)
|
||||||
@@ -79,25 +94,17 @@ func HandleSnakeEvents(snakeStore *snake.SnakeStore, svc *services.GameService,
|
|||||||
playerID := sessions.GetPlayerID(sm, r)
|
playerID := sessions.GetPlayerID(sm, r)
|
||||||
mySlot := si.GetPlayerSlot(playerID)
|
mySlot := si.GetPlayerSlot(playerID)
|
||||||
|
|
||||||
// Subscribe to game updates BEFORE creating SSE (following portigo pattern)
|
|
||||||
gameSub, gameCh, err := svc.SubscribeGameUpdates(gameID)
|
|
||||||
if err != nil {
|
|
||||||
http.Error(w, http.StatusText(http.StatusInternalServerError), http.StatusInternalServerError)
|
|
||||||
return
|
|
||||||
}
|
|
||||||
defer gameSub.Unsubscribe() //nolint:errcheck
|
|
||||||
|
|
||||||
sse := datastar.NewSSE(w, r, datastar.WithCompression(
|
sse := datastar.NewSSE(w, r, datastar.WithCompression(
|
||||||
datastar.WithBrotli(datastar.WithBrotliLevel(5)),
|
datastar.WithBrotli(datastar.WithBrotliLevel(5)),
|
||||||
))
|
))
|
||||||
|
|
||||||
chatCfg := svc.ChatConfig(gameID)
|
chatCfg := snakeChatConfig(gameID)
|
||||||
|
|
||||||
// Chat room (multiplayer only)
|
// Chat room (multiplayer only)
|
||||||
var room *chat.Room
|
var room *chat.Room
|
||||||
sg := si.GetGame()
|
sg := si.GetGame()
|
||||||
if sg.Mode == snake.ModeMultiplayer {
|
if sg.Mode == snake.ModeMultiplayer {
|
||||||
room = svc.ChatRoom(gameID)
|
room = chat.NewRoom(nc, snake.ChatSubject(gameID))
|
||||||
}
|
}
|
||||||
|
|
||||||
chatMessages := func() []chat.Message {
|
chatMessages := func() []chat.Message {
|
||||||
@@ -110,28 +117,46 @@ func HandleSnakeEvents(snakeStore *snake.SnakeStore, svc *services.GameService,
|
|||||||
patchAll := func() error {
|
patchAll := func() error {
|
||||||
si, ok = snakeStore.Get(gameID)
|
si, ok = snakeStore.Get(gameID)
|
||||||
if !ok {
|
if !ok {
|
||||||
return errors.New("game not found")
|
return fmt.Errorf("game not found")
|
||||||
}
|
}
|
||||||
mySlot = si.GetPlayerSlot(playerID)
|
mySlot = si.GetPlayerSlot(playerID)
|
||||||
sg = si.GetGame()
|
sg = si.GetGame()
|
||||||
return sse.PatchElementTempl(pages.GameContent(sg, mySlot, chatMessages(), chatCfg, gameID))
|
return sse.PatchElementTempl(pages.GameContent(sg, mySlot, chatMessages(), chatCfg, gameID))
|
||||||
}
|
}
|
||||||
|
|
||||||
// Send initial render
|
sendPing := func() error {
|
||||||
|
return sse.PatchSignals([]byte(fmt.Sprintf(`{"lastPing":%d}`, time.Now().UnixMilli())))
|
||||||
|
}
|
||||||
|
|
||||||
|
// Send initial render and ping
|
||||||
|
if err := sendPing(); err != nil {
|
||||||
|
return
|
||||||
|
}
|
||||||
if err := patchAll(); err != nil {
|
if err := patchAll(); err != nil {
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
heartbeat := time.NewTicker(1 * time.Second)
|
heartbeat := time.NewTicker(15 * time.Second)
|
||||||
defer heartbeat.Stop()
|
defer heartbeat.Stop()
|
||||||
|
|
||||||
|
// Subscribe to game updates via NATS
|
||||||
|
gameCh := make(chan *nats.Msg, 64)
|
||||||
|
gameSub, err := nc.ChanSubscribe(snake.GameSubject(gameID), gameCh)
|
||||||
|
if err != nil {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
defer gameSub.Unsubscribe() //nolint:errcheck
|
||||||
|
|
||||||
// Chat subscription (multiplayer only)
|
// Chat subscription (multiplayer only)
|
||||||
var chatCh <-chan chat.Message
|
var chatCh chan *nats.Msg
|
||||||
var cleanupChat func()
|
var chatSub *nats.Subscription
|
||||||
|
|
||||||
if room != nil {
|
if room != nil {
|
||||||
chatCh, cleanupChat = room.Subscribe()
|
chatCh, chatSub, err = room.Subscribe()
|
||||||
defer cleanupChat()
|
if err != nil {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
defer chatSub.Unsubscribe() //nolint:errcheck
|
||||||
}
|
}
|
||||||
|
|
||||||
ctx := r.Context()
|
ctx := r.Context()
|
||||||
@@ -141,8 +166,7 @@ func HandleSnakeEvents(snakeStore *snake.SnakeStore, svc *services.GameService,
|
|||||||
return
|
return
|
||||||
|
|
||||||
case <-heartbeat.C:
|
case <-heartbeat.C:
|
||||||
// Heartbeat refreshes game state to keep connection alive
|
if err := sendPing(); err != nil {
|
||||||
if err := patchAll(); err != nil {
|
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -160,10 +184,11 @@ func HandleSnakeEvents(snakeStore *snake.SnakeStore, svc *services.GameService,
|
|||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
case chatMsg, ok := <-chatCh:
|
case msg := <-chatCh:
|
||||||
if !ok {
|
if msg == nil {
|
||||||
continue
|
continue
|
||||||
}
|
}
|
||||||
|
chatMsg, _ := room.Receive(msg.Data)
|
||||||
err := sse.PatchElementTempl(
|
err := sse.PatchElementTempl(
|
||||||
chatcomponents.ChatMessage(chatMsg, chatCfg),
|
chatcomponents.ChatMessage(chatMsg, chatCfg),
|
||||||
datastar.WithSelectorID("snake-chat-history"),
|
datastar.WithSelectorID("snake-chat-history"),
|
||||||
@@ -209,7 +234,7 @@ type chatSignals struct {
|
|||||||
ChatMsg string `json:"chatMsg"`
|
ChatMsg string `json:"chatMsg"`
|
||||||
}
|
}
|
||||||
|
|
||||||
func HandleSendChat(snakeStore *snake.SnakeStore, svc *services.GameService, sm *scs.SessionManager) http.HandlerFunc {
|
func HandleSendChat(snakeStore *snake.SnakeStore, nc *nats.Conn, sm *scs.SessionManager) http.HandlerFunc {
|
||||||
return func(w http.ResponseWriter, r *http.Request) {
|
return func(w http.ResponseWriter, r *http.Request) {
|
||||||
gameID := chi.URLParam(r, "id")
|
gameID := chi.URLParam(r, "id")
|
||||||
si, ok := snakeStore.Get(gameID)
|
si, ok := snakeStore.Get(gameID)
|
||||||
@@ -242,7 +267,7 @@ func HandleSendChat(snakeStore *snake.SnakeStore, svc *services.GameService, sm
|
|||||||
Message: signals.ChatMsg,
|
Message: signals.ChatMsg,
|
||||||
}
|
}
|
||||||
|
|
||||||
room := svc.ChatRoom(gameID)
|
room := chat.NewRoom(nc, snake.ChatSubject(gameID))
|
||||||
room.Send(msg)
|
room.Send(msg)
|
||||||
|
|
||||||
sse := datastar.NewSSE(w, r)
|
sse := datastar.NewSSE(w, r)
|
||||||
|
|||||||
@@ -32,19 +32,19 @@ templ GamePage(sg *snake.SnakeGame, mySlot int, messages []chat.Message, chatCfg
|
|||||||
@layouts.Base("Snake") {
|
@layouts.Base("Snake") {
|
||||||
<main
|
<main
|
||||||
class="snake-wrapper flex flex-col items-center gap-4 p-4"
|
class="snake-wrapper flex flex-col items-center gap-4 p-4"
|
||||||
data-signals={ `{"chatMsg":""}` }
|
data-signals={ `{"chatMsg":"","lastPing":0}` }
|
||||||
data-init={ fmt.Sprintf("@get('/snake/%s/events',{requestCancellation:'disabled'})", gameID) }
|
data-init={ fmt.Sprintf("@get('/snake/%s/events',{requestCancellation:'disabled'})", gameID) }
|
||||||
data-on:keydown__throttle.100ms={ keydownScript(gameID) }
|
data-on:keydown__throttle.100ms={ keydownScript(gameID) }
|
||||||
tabindex="0"
|
tabindex="0"
|
||||||
>
|
>
|
||||||
|
@components.ConnectionIndicator()
|
||||||
@GameContent(sg, mySlot, messages, chatCfg, gameID)
|
@GameContent(sg, mySlot, messages, chatCfg, gameID)
|
||||||
</main>
|
</main>
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
templ GameContent(sg *snake.SnakeGame, mySlot int, messages []chat.Message, chatCfg chatcomponents.Config, gameID string) {
|
templ GameContent(sg *snake.SnakeGame, mySlot int, messages []chat.Message, chatCfg chatcomponents.Config, gameID string) {
|
||||||
<div id="game-content" class="flex flex-col items-center gap-4">
|
<div id="game-content">
|
||||||
@components.LiveClock()
|
|
||||||
@components.BackToLobby()
|
@components.BackToLobby()
|
||||||
<h1 class="text-3xl font-bold">~~~~</h1>
|
<h1 class="text-3xl font-bold">~~~~</h1>
|
||||||
@snakecomponents.PlayerList(sg, mySlot)
|
@snakecomponents.PlayerList(sg, mySlot)
|
||||||
|
|||||||
@@ -4,17 +4,17 @@ package snakegame
|
|||||||
import (
|
import (
|
||||||
"github.com/alexedwards/scs/v2"
|
"github.com/alexedwards/scs/v2"
|
||||||
"github.com/go-chi/chi/v5"
|
"github.com/go-chi/chi/v5"
|
||||||
|
"github.com/nats-io/nats.go"
|
||||||
|
|
||||||
"github.com/ryanhamamura/games/features/snakegame/services"
|
|
||||||
"github.com/ryanhamamura/games/snake"
|
"github.com/ryanhamamura/games/snake"
|
||||||
)
|
)
|
||||||
|
|
||||||
func SetupRoutes(router chi.Router, snakeStore *snake.SnakeStore, svc *services.GameService, sessions *scs.SessionManager) {
|
func SetupRoutes(router chi.Router, snakeStore *snake.SnakeStore, nc *nats.Conn, sessions *scs.SessionManager) {
|
||||||
router.Route("/snake/{id}", func(r chi.Router) {
|
router.Route("/snake/{id}", func(r chi.Router) {
|
||||||
r.Get("/", HandleSnakePage(snakeStore, svc, sessions))
|
r.Get("/", HandleSnakePage(snakeStore, sessions))
|
||||||
r.Get("/events", HandleSnakeEvents(snakeStore, svc, sessions))
|
r.Get("/events", HandleSnakeEvents(snakeStore, nc, sessions))
|
||||||
r.Post("/dir", HandleSetDirection(snakeStore, sessions))
|
r.Post("/dir", HandleSetDirection(snakeStore, sessions))
|
||||||
r.Post("/chat", HandleSendChat(snakeStore, svc, sessions))
|
r.Post("/chat", HandleSendChat(snakeStore, nc, sessions))
|
||||||
r.Post("/join", HandleSetNickname(snakeStore, sessions))
|
r.Post("/join", HandleSetNickname(snakeStore, sessions))
|
||||||
r.Post("/rematch", HandleRematch(snakeStore, sessions))
|
r.Post("/rematch", HandleRematch(snakeStore, sessions))
|
||||||
})
|
})
|
||||||
|
|||||||
@@ -1,62 +0,0 @@
|
|||||||
// Package services provides the game service layer for Snake,
|
|
||||||
// handling NATS subscriptions and chat room management.
|
|
||||||
package services
|
|
||||||
|
|
||||||
import (
|
|
||||||
"fmt"
|
|
||||||
|
|
||||||
"github.com/nats-io/nats.go"
|
|
||||||
|
|
||||||
"github.com/ryanhamamura/games/chat"
|
|
||||||
chatcomponents "github.com/ryanhamamura/games/chat/components"
|
|
||||||
"github.com/ryanhamamura/games/snake"
|
|
||||||
)
|
|
||||||
|
|
||||||
func snakeChatColor(slot int) string {
|
|
||||||
if slot >= 0 && slot < len(snake.SnakeColors) {
|
|
||||||
return snake.SnakeColors[slot]
|
|
||||||
}
|
|
||||||
return "#666"
|
|
||||||
}
|
|
||||||
|
|
||||||
// GameService manages NATS subscriptions and chat for Snake games.
|
|
||||||
type GameService struct {
|
|
||||||
nc *nats.Conn
|
|
||||||
}
|
|
||||||
|
|
||||||
// NewGameService creates a new game service.
|
|
||||||
func NewGameService(nc *nats.Conn) *GameService {
|
|
||||||
return &GameService{
|
|
||||||
nc: nc,
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// SubscribeGameUpdates returns a NATS subscription and channel for game state updates.
|
|
||||||
func (s *GameService) SubscribeGameUpdates(gameID string) (*nats.Subscription, <-chan *nats.Msg, error) {
|
|
||||||
ch := make(chan *nats.Msg, 64)
|
|
||||||
sub, err := s.nc.ChanSubscribe(snake.GameSubject(gameID), ch)
|
|
||||||
if err != nil {
|
|
||||||
return nil, nil, fmt.Errorf("subscribing to game updates: %w", err)
|
|
||||||
}
|
|
||||||
return sub, ch, nil
|
|
||||||
}
|
|
||||||
|
|
||||||
// ChatConfig returns the chat configuration for a game.
|
|
||||||
func (s *GameService) ChatConfig(gameID string) chatcomponents.Config {
|
|
||||||
return chatcomponents.Config{
|
|
||||||
CSSPrefix: "snake",
|
|
||||||
PostURL: fmt.Sprintf("/snake/%s/chat", gameID),
|
|
||||||
Color: snakeChatColor,
|
|
||||||
StopKeyPropagation: true,
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// ChatRoom returns a chat room for a game (ephemeral, not persisted).
|
|
||||||
func (s *GameService) ChatRoom(gameID string) *chat.Room {
|
|
||||||
return chat.NewRoom(s.nc, snake.ChatSubject(gameID))
|
|
||||||
}
|
|
||||||
|
|
||||||
// PublishGameUpdate sends a notification that the game state has changed.
|
|
||||||
func (s *GameService) PublishGameUpdate(gameID string) error {
|
|
||||||
return s.nc.Publish(snake.GameSubject(gameID), nil)
|
|
||||||
}
|
|
||||||
4
go.mod
4
go.mod
@@ -68,7 +68,6 @@ require (
|
|||||||
github.com/aws/aws-sdk-go-v2/service/ssooidc v1.35.12 // indirect
|
github.com/aws/aws-sdk-go-v2/service/ssooidc v1.35.12 // indirect
|
||||||
github.com/aws/aws-sdk-go-v2/service/sts v1.41.5 // indirect
|
github.com/aws/aws-sdk-go-v2/service/sts v1.41.5 // indirect
|
||||||
github.com/aws/smithy-go v1.24.0 // indirect
|
github.com/aws/smithy-go v1.24.0 // indirect
|
||||||
github.com/benbjohnson/hashfs v0.2.2 // indirect
|
|
||||||
github.com/bep/godartsass/v2 v2.5.0 // indirect
|
github.com/bep/godartsass/v2 v2.5.0 // indirect
|
||||||
github.com/bep/golibsass v1.2.0 // indirect
|
github.com/bep/golibsass v1.2.0 // indirect
|
||||||
github.com/bgentry/go-netrc v0.0.0-20140422174119-9fd32a8b3d3d // indirect
|
github.com/bgentry/go-netrc v0.0.0-20140422174119-9fd32a8b3d3d // indirect
|
||||||
@@ -171,9 +170,6 @@ require (
|
|||||||
github.com/rivo/uniseg v0.4.7 // indirect
|
github.com/rivo/uniseg v0.4.7 // indirect
|
||||||
github.com/riza-io/grpc-go v0.2.0 // indirect
|
github.com/riza-io/grpc-go v0.2.0 // indirect
|
||||||
github.com/sajari/fuzzy v1.0.0 // indirect
|
github.com/sajari/fuzzy v1.0.0 // indirect
|
||||||
github.com/samber/lo v1.52.0 // indirect
|
|
||||||
github.com/samber/slog-common v0.20.0 // indirect
|
|
||||||
github.com/samber/slog-zerolog/v2 v2.9.1 // indirect
|
|
||||||
github.com/segmentio/asm v1.2.1 // indirect
|
github.com/segmentio/asm v1.2.1 // indirect
|
||||||
github.com/sethvargo/go-retry v0.3.0 // indirect
|
github.com/sethvargo/go-retry v0.3.0 // indirect
|
||||||
github.com/shopspring/decimal v1.4.0 // indirect
|
github.com/shopspring/decimal v1.4.0 // indirect
|
||||||
|
|||||||
8
go.sum
8
go.sum
@@ -136,8 +136,6 @@ github.com/aymanbagabas/go-udiff v0.3.1/go.mod h1:G0fsKmG+P6ylD0r6N/KgQD/nWzgfnl
|
|||||||
github.com/aymerick/douceur v0.2.0 h1:Mv+mAeH1Q+n9Fr+oyamOlAkUNPWPlA8PPGR0QAaYuPk=
|
github.com/aymerick/douceur v0.2.0 h1:Mv+mAeH1Q+n9Fr+oyamOlAkUNPWPlA8PPGR0QAaYuPk=
|
||||||
github.com/aymerick/douceur v0.2.0/go.mod h1:wlT5vV2O3h55X9m7iVYN0TBM0NH/MmbLnd30/FjWUq4=
|
github.com/aymerick/douceur v0.2.0/go.mod h1:wlT5vV2O3h55X9m7iVYN0TBM0NH/MmbLnd30/FjWUq4=
|
||||||
github.com/benbjohnson/clock v1.1.0/go.mod h1:J11/hYXuz8f4ySSvYwY0FKfm+ezbsZBKZxNJlLklBHA=
|
github.com/benbjohnson/clock v1.1.0/go.mod h1:J11/hYXuz8f4ySSvYwY0FKfm+ezbsZBKZxNJlLklBHA=
|
||||||
github.com/benbjohnson/hashfs v0.2.2 h1:vFZtksphM5LcnMRFctj49jCUkCc7wp3NP6INyfjkse4=
|
|
||||||
github.com/benbjohnson/hashfs v0.2.2/go.mod h1:7OMXaMVo1YkfiIPxKrl7OXkUTUgWjmsAKyR+E6xDIRM=
|
|
||||||
github.com/bep/clocks v0.5.0 h1:hhvKVGLPQWRVsBP/UB7ErrHYIO42gINVbvqxvYTPVps=
|
github.com/bep/clocks v0.5.0 h1:hhvKVGLPQWRVsBP/UB7ErrHYIO42gINVbvqxvYTPVps=
|
||||||
github.com/bep/clocks v0.5.0/go.mod h1:SUq3q+OOq41y2lRQqH5fsOoxN8GbxSiT6jvoVVLCVhU=
|
github.com/bep/clocks v0.5.0/go.mod h1:SUq3q+OOq41y2lRQqH5fsOoxN8GbxSiT6jvoVVLCVhU=
|
||||||
github.com/bep/debounce v1.2.1 h1:v67fRdBA9UQu2NhLFXrSg0Brw7CexQekrBwDMM8bzeY=
|
github.com/bep/debounce v1.2.1 h1:v67fRdBA9UQu2NhLFXrSg0Brw7CexQekrBwDMM8bzeY=
|
||||||
@@ -567,12 +565,6 @@ github.com/rs/zerolog v1.34.0/go.mod h1:bJsvje4Z08ROH4Nhs5iH600c3IkWhwp44iRc54W6
|
|||||||
github.com/russross/blackfriday/v2 v2.1.0/go.mod h1:+Rmxgy9KzJVeS9/2gXHxylqXiyQDYRxCVz55jmeOWTM=
|
github.com/russross/blackfriday/v2 v2.1.0/go.mod h1:+Rmxgy9KzJVeS9/2gXHxylqXiyQDYRxCVz55jmeOWTM=
|
||||||
github.com/sajari/fuzzy v1.0.0 h1:+FmwVvJErsd0d0hAPlj4CxqxUtQY/fOoY0DwX4ykpRY=
|
github.com/sajari/fuzzy v1.0.0 h1:+FmwVvJErsd0d0hAPlj4CxqxUtQY/fOoY0DwX4ykpRY=
|
||||||
github.com/sajari/fuzzy v1.0.0/go.mod h1:OjYR6KxoWOe9+dOlXeiCJd4dIbED4Oo8wpS89o0pwOo=
|
github.com/sajari/fuzzy v1.0.0/go.mod h1:OjYR6KxoWOe9+dOlXeiCJd4dIbED4Oo8wpS89o0pwOo=
|
||||||
github.com/samber/lo v1.52.0 h1:Rvi+3BFHES3A8meP33VPAxiBZX/Aws5RxrschYGjomw=
|
|
||||||
github.com/samber/lo v1.52.0/go.mod h1:4+MXEGsJzbKGaUEQFKBq2xtfuznW9oz/WrgyzMzRoM0=
|
|
||||||
github.com/samber/slog-common v0.20.0 h1:WaLnm/aCvBJSk5nR5aXZTFBaV0B47A+AEaEOiZDeUnc=
|
|
||||||
github.com/samber/slog-common v0.20.0/go.mod h1:+Ozat1jgnnE59UAlmNX1IF3IByHsODnnwf9jUcBZ+m8=
|
|
||||||
github.com/samber/slog-zerolog/v2 v2.9.1 h1:RMOq8XqzfuGx1X0TEIlS9OXbbFmqLY2/wJppghz66YY=
|
|
||||||
github.com/samber/slog-zerolog/v2 v2.9.1/go.mod h1:DQYYve14WgCRN/XnKeHl4266jXK0DgYkYXkfZ4Fp98k=
|
|
||||||
github.com/sebdah/goldie/v2 v2.8.0 h1:dZb9wR8q5++oplmEiJT+U/5KyotVD+HNGCAc5gNr8rc=
|
github.com/sebdah/goldie/v2 v2.8.0 h1:dZb9wR8q5++oplmEiJT+U/5KyotVD+HNGCAc5gNr8rc=
|
||||||
github.com/sebdah/goldie/v2 v2.8.0/go.mod h1:oZ9fp0+se1eapSRjfYbsV/0Hqhbuu3bJVvKI/NNtssI=
|
github.com/sebdah/goldie/v2 v2.8.0/go.mod h1:oZ9fp0+se1eapSRjfYbsV/0Hqhbuu3bJVvKI/NNtssI=
|
||||||
github.com/segmentio/asm v1.2.1 h1:DTNbBqs57ioxAD4PrArqftgypG4/qNpXoJx8TVXxPR0=
|
github.com/segmentio/asm v1.2.1 h1:DTNbBqs57ioxAD4PrArqftgypG4/qNpXoJx8TVXxPR0=
|
||||||
|
|||||||
@@ -5,11 +5,10 @@ import (
|
|||||||
"net/http"
|
"net/http"
|
||||||
"time"
|
"time"
|
||||||
|
|
||||||
"github.com/go-chi/chi/v5/middleware"
|
"github.com/ryanhamamura/games/config"
|
||||||
|
|
||||||
"github.com/rs/zerolog"
|
"github.com/rs/zerolog"
|
||||||
"github.com/rs/zerolog/log"
|
"github.com/rs/zerolog/log"
|
||||||
|
|
||||||
"github.com/ryanhamamura/games/config"
|
|
||||||
)
|
)
|
||||||
|
|
||||||
const (
|
const (
|
||||||
@@ -65,15 +64,25 @@ func colorLatency(d time.Duration, useColor bool) string {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
type responseWriter struct {
|
||||||
|
http.ResponseWriter
|
||||||
|
status int
|
||||||
|
}
|
||||||
|
|
||||||
|
func (rw *responseWriter) WriteHeader(code int) {
|
||||||
|
rw.status = code
|
||||||
|
rw.ResponseWriter.WriteHeader(code)
|
||||||
|
}
|
||||||
|
|
||||||
func RequestLogger(logger *zerolog.Logger, env config.Environment) func(http.Handler) http.Handler {
|
func RequestLogger(logger *zerolog.Logger, env config.Environment) func(http.Handler) http.Handler {
|
||||||
return func(next http.Handler) http.Handler {
|
return func(next http.Handler) http.Handler {
|
||||||
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||||
start := time.Now()
|
start := time.Now()
|
||||||
ww := middleware.NewWrapResponseWriter(w, r.ProtoMajor)
|
rw := &responseWriter{ResponseWriter: w}
|
||||||
|
|
||||||
next.ServeHTTP(ww, r)
|
next.ServeHTTP(rw, r)
|
||||||
|
|
||||||
status := ww.Status()
|
status := rw.status
|
||||||
if status == 0 {
|
if status == 0 {
|
||||||
status = http.StatusOK
|
status = http.StatusOK
|
||||||
}
|
}
|
||||||
|
|||||||
28
main.go
28
main.go
@@ -2,6 +2,7 @@ package main
|
|||||||
|
|
||||||
import (
|
import (
|
||||||
"context"
|
"context"
|
||||||
|
"embed"
|
||||||
"fmt"
|
"fmt"
|
||||||
"log/slog"
|
"log/slog"
|
||||||
"net"
|
"net"
|
||||||
@@ -10,12 +11,6 @@ import (
|
|||||||
"syscall"
|
"syscall"
|
||||||
"time"
|
"time"
|
||||||
|
|
||||||
"github.com/go-chi/chi/v5"
|
|
||||||
"github.com/go-chi/chi/v5/middleware"
|
|
||||||
"github.com/rs/zerolog/log"
|
|
||||||
slogzerolog "github.com/samber/slog-zerolog/v2"
|
|
||||||
"golang.org/x/sync/errgroup"
|
|
||||||
|
|
||||||
"github.com/ryanhamamura/games/config"
|
"github.com/ryanhamamura/games/config"
|
||||||
"github.com/ryanhamamura/games/connect4"
|
"github.com/ryanhamamura/games/connect4"
|
||||||
"github.com/ryanhamamura/games/db"
|
"github.com/ryanhamamura/games/db"
|
||||||
@@ -26,19 +21,22 @@ import (
|
|||||||
"github.com/ryanhamamura/games/sessions"
|
"github.com/ryanhamamura/games/sessions"
|
||||||
"github.com/ryanhamamura/games/snake"
|
"github.com/ryanhamamura/games/snake"
|
||||||
"github.com/ryanhamamura/games/version"
|
"github.com/ryanhamamura/games/version"
|
||||||
|
|
||||||
|
"github.com/go-chi/chi/v5"
|
||||||
|
"github.com/go-chi/chi/v5/middleware"
|
||||||
|
"github.com/rs/zerolog/log"
|
||||||
|
"golang.org/x/sync/errgroup"
|
||||||
)
|
)
|
||||||
|
|
||||||
|
//go:embed assets
|
||||||
|
var assets embed.FS
|
||||||
|
|
||||||
func main() {
|
func main() {
|
||||||
ctx, cancel := signal.NotifyContext(context.Background(), syscall.SIGINT, syscall.SIGTERM)
|
ctx, cancel := signal.NotifyContext(context.Background(), syscall.SIGINT, syscall.SIGTERM)
|
||||||
defer cancel()
|
defer cancel()
|
||||||
|
|
||||||
cfg := config.Global
|
cfg := config.Global
|
||||||
zerologLogger := logging.SetupLogger(cfg.Environment, cfg.LogLevel)
|
logging.SetupLogger(cfg.Environment, cfg.LogLevel)
|
||||||
slog.SetDefault(slog.New(slogzerolog.Option{
|
|
||||||
Level: slogzerolog.ZeroLogLeveler{Logger: zerologLogger},
|
|
||||||
Logger: zerologLogger,
|
|
||||||
NoTimestamp: true,
|
|
||||||
}.NewZerologHandler()))
|
|
||||||
|
|
||||||
if err := run(ctx); err != nil && err != http.ErrServerClosed {
|
if err := run(ctx); err != nil && err != http.ErrServerClosed {
|
||||||
log.Fatal().Err(err).Msg("server error")
|
log.Fatal().Err(err).Msg("server error")
|
||||||
@@ -93,7 +91,7 @@ func run(ctx context.Context) error {
|
|||||||
sessionManager.LoadAndSave,
|
sessionManager.LoadAndSave,
|
||||||
)
|
)
|
||||||
|
|
||||||
router.SetupRoutes(r, queries, sessionManager, nc, store, snakeStore)
|
router.SetupRoutes(r, queries, sessionManager, nc, store, snakeStore, assets)
|
||||||
|
|
||||||
// HTTP server
|
// HTTP server
|
||||||
srv := &http.Server{
|
srv := &http.Server{
|
||||||
@@ -103,10 +101,6 @@ func run(ctx context.Context) error {
|
|||||||
BaseContext: func(l net.Listener) context.Context {
|
BaseContext: func(l net.Listener) context.Context {
|
||||||
return egctx
|
return egctx
|
||||||
},
|
},
|
||||||
ErrorLog: slog.NewLogLogger(
|
|
||||||
slog.Default().Handler(),
|
|
||||||
slog.LevelError,
|
|
||||||
),
|
|
||||||
}
|
}
|
||||||
|
|
||||||
eg.Go(func() error {
|
eg.Go(func() error {
|
||||||
|
|||||||
@@ -2,25 +2,24 @@
|
|||||||
package router
|
package router
|
||||||
|
|
||||||
import (
|
import (
|
||||||
|
"embed"
|
||||||
|
"io/fs"
|
||||||
"net/http"
|
"net/http"
|
||||||
"sync"
|
"sync"
|
||||||
|
|
||||||
"github.com/alexedwards/scs/v2"
|
|
||||||
"github.com/go-chi/chi/v5"
|
|
||||||
"github.com/nats-io/nats.go"
|
|
||||||
"github.com/starfederation/datastar-go/datastar"
|
|
||||||
|
|
||||||
"github.com/ryanhamamura/games/assets"
|
|
||||||
"github.com/ryanhamamura/games/config"
|
"github.com/ryanhamamura/games/config"
|
||||||
"github.com/ryanhamamura/games/connect4"
|
"github.com/ryanhamamura/games/connect4"
|
||||||
"github.com/ryanhamamura/games/db/repository"
|
"github.com/ryanhamamura/games/db/repository"
|
||||||
"github.com/ryanhamamura/games/features/auth"
|
"github.com/ryanhamamura/games/features/auth"
|
||||||
"github.com/ryanhamamura/games/features/c4game"
|
"github.com/ryanhamamura/games/features/c4game"
|
||||||
c4services "github.com/ryanhamamura/games/features/c4game/services"
|
|
||||||
"github.com/ryanhamamura/games/features/lobby"
|
"github.com/ryanhamamura/games/features/lobby"
|
||||||
"github.com/ryanhamamura/games/features/snakegame"
|
"github.com/ryanhamamura/games/features/snakegame"
|
||||||
snakeservices "github.com/ryanhamamura/games/features/snakegame/services"
|
|
||||||
"github.com/ryanhamamura/games/snake"
|
"github.com/ryanhamamura/games/snake"
|
||||||
|
|
||||||
|
"github.com/alexedwards/scs/v2"
|
||||||
|
"github.com/go-chi/chi/v5"
|
||||||
|
"github.com/nats-io/nats.go"
|
||||||
|
"github.com/starfederation/datastar-go/datastar"
|
||||||
)
|
)
|
||||||
|
|
||||||
func SetupRoutes(
|
func SetupRoutes(
|
||||||
@@ -30,23 +29,21 @@ func SetupRoutes(
|
|||||||
nc *nats.Conn,
|
nc *nats.Conn,
|
||||||
store *connect4.Store,
|
store *connect4.Store,
|
||||||
snakeStore *snake.SnakeStore,
|
snakeStore *snake.SnakeStore,
|
||||||
|
assets embed.FS,
|
||||||
) {
|
) {
|
||||||
// Static assets
|
// Static assets
|
||||||
router.Handle("/assets/*", assets.Handler())
|
subFS, _ := fs.Sub(assets, "assets")
|
||||||
|
router.Handle("/assets/*", http.StripPrefix("/assets/", http.FileServerFS(subFS)))
|
||||||
|
|
||||||
// Hot-reload for development
|
// Hot-reload for development
|
||||||
if config.Global.Environment == config.Dev {
|
if config.Global.Environment == config.Dev {
|
||||||
setupReload(router)
|
setupReload(router)
|
||||||
}
|
}
|
||||||
|
|
||||||
// Services
|
|
||||||
c4Svc := c4services.NewGameService(nc, queries)
|
|
||||||
snakeSvc := snakeservices.NewGameService(nc)
|
|
||||||
|
|
||||||
auth.SetupRoutes(router, queries, sessions)
|
auth.SetupRoutes(router, queries, sessions)
|
||||||
lobby.SetupRoutes(router, queries, sessions, store, snakeStore)
|
lobby.SetupRoutes(router, queries, sessions, store, snakeStore)
|
||||||
c4game.SetupRoutes(router, store, c4Svc, sessions)
|
c4game.SetupRoutes(router, store, nc, sessions, queries)
|
||||||
snakegame.SetupRoutes(router, snakeStore, snakeSvc, sessions)
|
snakegame.SetupRoutes(router, snakeStore, nc, sessions)
|
||||||
}
|
}
|
||||||
|
|
||||||
func setupReload(router chi.Router) {
|
func setupReload(router chi.Router) {
|
||||||
|
|||||||
@@ -33,7 +33,7 @@ func SetupSessionManager(db *sql.DB) (*scs.SessionManager, func()) {
|
|||||||
sessionManager.Cookie.Name = "games_session"
|
sessionManager.Cookie.Name = "games_session"
|
||||||
sessionManager.Cookie.Path = "/"
|
sessionManager.Cookie.Path = "/"
|
||||||
sessionManager.Cookie.HttpOnly = true
|
sessionManager.Cookie.HttpOnly = true
|
||||||
sessionManager.Cookie.Secure = false
|
sessionManager.Cookie.Secure = true
|
||||||
sessionManager.Cookie.SameSite = http.SameSiteLaxMode
|
sessionManager.Cookie.SameSite = http.SameSiteLaxMode
|
||||||
|
|
||||||
slog.Info("session manager configured")
|
slog.Info("session manager configured")
|
||||||
|
|||||||
Reference in New Issue
Block a user