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