feat: migrar backend unificado a Go 1.27 + SPA Vite embebido
This commit is contained in:
@@ -0,0 +1,55 @@
|
||||
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)
|
||||
})
|
||||
}
|
||||
Reference in New Issue
Block a user