Phase 0: backend + frontend scaffold, single-binary build
Gadfly review (reusable) / review (pull_request) Successful in 10m8s
Adversarial Review (Gadfly) / review (pull_request) Successful in 10m9s

Implements the Pansy v1 scaffold (epic #20, phase 0).

#1 Backend: Go module (pure-Go, builds with CGO_ENABLED=0), env config,
   gin server with slog + recovery + /api/v1/healthz, modernc SQLite store
   with WAL/busy_timeout/foreign_keys pragmas, embedded numbered-migration
   runner, full initial schema (users, sessions, gardens, garden_shares,
   garden_objects, plants, plantings), domain structs + sentinel errors,
   graceful shutdown.

#2 Frontend: Vite + React 19 + TS (strict) + Tailwind 4 + TanStack
   Router/Query, typed /api/v1 fetch wrapper (ApiError carries status +
   body so later issues can read 409 conflict rows), dev proxy /api -> :8080,
   responsive app shell with stub pages for all five routes.

#3 Single binary: //go:embed of the web build with a committed placeholder,
   SPA fallback (deep links, immutable asset caching, JSON 404 for unmatched
   /api and missing assets), Makefile (web/build/dev/test), README quickstart
   + env var table.

Verified: go build/vet/test clean (CGO off); binary migrates idempotently and
serves healthz; web tsc + build clean; integrated binary serves the SPA, deep
links, and correct cache headers; app mounts and navigates all five routes at
desktop and 375px widths.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
Claude-Session: https://claude.ai/code/session_01JdQpdYYsTgtkJBxbcpAszi
This commit is contained in:
2026-07-18 14:52:05 -04:00
co-authored by Claude Opus 4.8
parent 76d18da542
commit 91da9ff945
36 changed files with 4578 additions and 0 deletions
+44
View File
@@ -0,0 +1,44 @@
// Package api wires pansy's HTTP surface: a gin engine with structured logging
// and panic recovery, the versioned JSON API under /api/v1, and (via spa.go) the
// embedded single-page-app fallback. Handlers stay thin — decode, call the
// service layer, encode — so all business logic and permission checks live in
// internal/service (added by later issues).
package api
import (
"log/slog"
"net/http"
"github.com/gin-gonic/gin"
sloggin "github.com/samber/slog-gin"
"gitea.stevedudenhoeffer.com/steve/pansy/internal/config"
)
func init() {
// Quiet gin's default debug output; we log via slog-gin instead.
gin.SetMode(gin.ReleaseMode)
}
// New builds the gin engine with the standard middleware stack and registers the
// API routes. The embedded SPA fallback is registered separately by the caller
// via RegisterSPA (see spa.go) so the API can be built and tested without a web
// build present.
func New(cfg *config.Config) *gin.Engine {
r := gin.New()
r.Use(sloggin.New(slog.Default()), gin.Recovery())
if err := r.SetTrustedProxies(cfg.TrustedProxies); err != nil {
slog.Warn("api: failed to set trusted proxies", "error", err)
}
v1 := r.Group("/api/v1")
v1.GET("/healthz", healthz)
return r
}
// healthz is a liveness probe: always returns {"ok": true} when the server is up.
func healthz(c *gin.Context) {
c.JSON(http.StatusOK, gin.H{"ok": true})
}
+78
View File
@@ -0,0 +1,78 @@
package api
import (
"io/fs"
"net/http"
"path"
"strings"
"github.com/gin-gonic/gin"
)
// RegisterSPA serves the embedded single-page app for every route gin didn't
// otherwise match. A request whose path maps to a real file (e.g. a hashed asset
// bundle) is served directly; any other non-API path falls back to index.html so
// client-side deep links like /gardens/42 load the app. Unmatched /api paths
// return a JSON 404 rather than HTML.
func RegisterSPA(r *gin.Engine, dist fs.FS) {
fileServer := http.FileServer(http.FS(dist))
r.NoRoute(func(c *gin.Context) {
reqPath := c.Request.URL.Path
if strings.HasPrefix(reqPath, "/api/") {
c.JSON(http.StatusNotFound, gin.H{"error": gin.H{
"code": "NOT_FOUND", "message": "no such endpoint",
}})
return
}
if c.Request.Method != http.MethodGet && c.Request.Method != http.MethodHead {
c.JSON(http.StatusMethodNotAllowed, gin.H{"error": gin.H{
"code": "METHOD_NOT_ALLOWED", "message": "method not allowed",
}})
return
}
name := strings.TrimPrefix(path.Clean(reqPath), "/")
if name == "" {
name = "index.html"
}
if f, err := dist.Open(name); err == nil {
f.Close()
// Vite emits content-hashed filenames under assets/, so those are safe
// to cache forever; index.html must always revalidate to pick up new builds.
if strings.HasPrefix(name, "assets/") {
c.Header("Cache-Control", "public, max-age=31536000, immutable")
} else {
c.Header("Cache-Control", "no-cache")
}
fileServer.ServeHTTP(c.Writer, c.Request)
return
}
// A missing file under assets/ is a genuine 404, not a client route:
// falling back to index.html would return HTML with a 200 for a .js/.css
// request, which the browser rejects with a confusing MIME-type error.
if strings.HasPrefix(name, "assets/") {
c.JSON(http.StatusNotFound, gin.H{"error": gin.H{
"code": "NOT_FOUND", "message": "asset not found",
}})
return
}
serveIndex(c, dist)
})
}
// serveIndex writes index.html as the SPA fallback for an unmatched client route.
func serveIndex(c *gin.Context, dist fs.FS) {
data, err := fs.ReadFile(dist, "index.html")
if err != nil {
c.String(http.StatusInternalServerError, "index.html missing from build")
return
}
c.Header("Cache-Control", "no-cache")
c.Data(http.StatusOK, "text/html; charset=utf-8", data)
}
+95
View File
@@ -0,0 +1,95 @@
package api
import (
"net/http"
"net/http/httptest"
"strings"
"testing"
"testing/fstest"
"github.com/gin-gonic/gin"
)
func testEngine() *gin.Engine {
gin.SetMode(gin.TestMode)
r := gin.New()
// A real API route so unmatched /api/* paths reach NoRoute (as in production).
r.GET("/api/v1/healthz", func(c *gin.Context) { c.JSON(http.StatusOK, gin.H{"ok": true}) })
dist := fstest.MapFS{
"index.html": &fstest.MapFile{Data: []byte(`<!doctype html><div id="root"></div>`)},
"assets/app-abc123.js": &fstest.MapFile{Data: []byte(`console.log(1)`)},
}
RegisterSPA(r, dist)
return r
}
func do(t *testing.T, r *gin.Engine, method, path string) *httptest.ResponseRecorder {
t.Helper()
w := httptest.NewRecorder()
r.ServeHTTP(w, httptest.NewRequest(method, path, nil))
return w
}
func TestSPAServesHashedAssetImmutable(t *testing.T) {
w := do(t, testEngine(), http.MethodGet, "/assets/app-abc123.js")
if w.Code != http.StatusOK {
t.Fatalf("status = %d, want 200", w.Code)
}
if cc := w.Header().Get("Cache-Control"); !strings.Contains(cc, "immutable") {
t.Errorf("Cache-Control = %q, want immutable", cc)
}
if ct := w.Header().Get("Content-Type"); !strings.Contains(ct, "javascript") {
t.Errorf("Content-Type = %q, want javascript", ct)
}
}
func TestSPAServesIndexNoCache(t *testing.T) {
w := do(t, testEngine(), http.MethodGet, "/")
if w.Code != http.StatusOK {
t.Fatalf("status = %d, want 200", w.Code)
}
if cc := w.Header().Get("Cache-Control"); cc != "no-cache" {
t.Errorf("Cache-Control = %q, want no-cache", cc)
}
}
func TestSPAFallbackForClientRoute(t *testing.T) {
// A deep link with no matching file returns index.html so client routing works.
w := do(t, testEngine(), http.MethodGet, "/gardens/42")
if w.Code != http.StatusOK {
t.Fatalf("status = %d, want 200", w.Code)
}
if !strings.Contains(w.Body.String(), `id="root"`) {
t.Errorf("expected index.html body, got %q", w.Body.String())
}
}
func TestSPAMissingAssetIs404(t *testing.T) {
// A missing asset must NOT fall back to index.html (which would be a 200 of
// HTML for a .js request — a MIME-type error in the browser).
w := do(t, testEngine(), http.MethodGet, "/assets/missing-xyz.js")
if w.Code != http.StatusNotFound {
t.Fatalf("status = %d, want 404", w.Code)
}
if ct := w.Header().Get("Content-Type"); !strings.Contains(ct, "json") {
t.Errorf("Content-Type = %q, want json", ct)
}
}
func TestSPAUnmatchedAPIIs404JSON(t *testing.T) {
w := do(t, testEngine(), http.MethodGet, "/api/v1/nope")
if w.Code != http.StatusNotFound {
t.Fatalf("status = %d, want 404", w.Code)
}
if ct := w.Header().Get("Content-Type"); !strings.Contains(ct, "json") {
t.Errorf("Content-Type = %q, want json (not the SPA HTML)", ct)
}
}
func TestSPARejectsNonGET(t *testing.T) {
w := do(t, testEngine(), http.MethodPost, "/gardens")
if w.Code != http.StatusMethodNotAllowed {
t.Fatalf("status = %d, want 405", w.Code)
}
}