Files
pansy/internal/api/spa.go
T
steveandClaude Opus 4.8 91da9ff945
Gadfly review (reusable) / review (pull_request) Successful in 10m8s
Adversarial Review (Gadfly) / review (pull_request) Successful in 10m9s
Phase 0: backend + frontend scaffold, single-binary build
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
2026-07-18 14:52:05 -04:00

79 lines
2.3 KiB
Go

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)
}