Files
jiggablend/web/embed.go
2025-11-27 00:46:48 -06:00

46 lines
944 B
Go

package web
import (
"embed"
"io/fs"
"net/http"
"strings"
)
//go:embed dist/*
var distFS embed.FS
// GetFileSystem returns an http.FileSystem for the embedded web UI files
func GetFileSystem() http.FileSystem {
subFS, err := fs.Sub(distFS, "dist")
if err != nil {
panic(err)
}
return http.FS(subFS)
}
// SPAHandler returns an http.Handler that serves the embedded SPA
// It serves static files if they exist, otherwise falls back to index.html
func SPAHandler() http.Handler {
fsys := GetFileSystem()
fileServer := http.FileServer(fsys)
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
path := r.URL.Path
// Try to open the file
f, err := fsys.Open(strings.TrimPrefix(path, "/"))
if err != nil {
// File doesn't exist, serve index.html for SPA routing
r.URL.Path = "/"
fileServer.ServeHTTP(w, r)
return
}
f.Close()
// File exists, serve it
fileServer.ServeHTTP(w, r)
})
}