Files
move-data-nas/internal/webui/embed.go
T
darroyo 596981b63b Bump version to 1.0.3
webui: use fs.Sub to fix embed FS root so static assets are found

Previously http.FileServer searched for assets/foo.css in the embed FS
rooted at dist/, but only paths starting with dist/ resolve. fs.Sub
strips the dist/ prefix so FileServer finds the actual files.
2026-07-07 19:46:03 -04:00

48 lines
1.0 KiB
Go

package webui
import (
"embed"
"io/fs"
"net/http"
)
//go:embed dist
var DistFS embed.FS
var distSub, _ = fs.Sub(DistFS, "dist")
func ServeHTTP() http.Handler {
return http.FileServer(http.FS(distSub))
}
func ServeSPA() http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
path := r.URL.Path
if path == "/favicon.ico" {
w.WriteHeader(http.StatusNoContent)
return
}
if path == "/" || !isStaticAsset(path) {
data, err := DistFS.ReadFile("dist/index.html")
if err != nil {
http.Error(w, "not found", http.StatusNotFound)
return
}
w.Header().Set("Content-Type", "text/html")
w.Write(data)
return
}
http.FileServer(http.FS(distSub)).ServeHTTP(w, r)
})
}
func isStaticAsset(path string) bool {
exts := []string{".js", ".css", ".png", ".jpg", ".jpeg", ".gif", ".svg", ".ico", ".woff", ".woff2", ".ttf", ".eot", ".map"}
for _, ext := range exts {
if len(path) > len(ext) && path[len(path)-len(ext):] == ext {
return true
}
}
return false
}