596981b63b
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.
48 lines
1.0 KiB
Go
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
|
|
}
|