package spa import ( "embed" "io/fs" "net/http" "path" "strings" ) //go:embed all:dist var distFS embed.FS // Handler serves the embedded Vite React SPA with client-side routing fallback, // immutable caching for /assets/*, and no-cache for index.html and /sw.js. func Handler() http.Handler { sub, err := fs.Sub(distFS, "dist") if err != nil { panic(err) } fileServer := http.FileServer(http.FS(sub)) return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { p := strings.TrimPrefix(path.Clean("/"+r.URL.Path), "/") if p == "" { p = "index.html" } // Try exact static file first if f, err := sub.Open(p); err == nil { stat, statErr := f.Stat() _ = f.Close() if statErr == nil && !stat.IsDir() { if strings.HasPrefix(p, "assets/") { w.Header().Set("Cache-Control", "public, max-age=31536000, immutable") } else if p == "sw.js" || p == "index.html" { w.Header().Set("Cache-Control", "no-cache, no-store, must-revalidate") } fileServer.ServeHTTP(w, r) return } } // SPA fallback to index.html for client routes indexBytes, err := fs.ReadFile(sub, "index.html") if err != nil { http.NotFound(w, r) return } w.Header().Set("Content-Type", "text/html; charset=utf-8") w.Header().Set("Cache-Control", "no-cache, no-store, must-revalidate") w.WriteHeader(http.StatusOK) _, _ = w.Write(indexBytes) }) }