// Package dashboard serves the single binary's SPA: archie.html and its // assets from the embedded build. Every other route belongs to a module. package dashboard import ( "io/fs" "net/http" "strings" "github.com/samcharles93/archie-core/internal/platform/httpjson" ) const page = "archie.html" // Routes serves the SPA from dist on mux. A path under /api/ that no module // claimed is a JSON 404, never the page. With no build embedded, the page // says how to build it. // // One pattern serves both: a method-scoped fallback beside the /api/ catch-all // is a ServeMux conflict, since Go matches the more general pattern for the // methods the other doesn't name. func Routes(mux *http.ServeMux, dist fs.FS) { mux.Handle("/", handler(dist)) } func handler(dist fs.FS) http.Handler { if dist == nil { return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { if strings.HasPrefix(r.URL.Path, "/api/") { httpjson.Error(w, http.StatusNotFound, "no such route") return } http.Error(w, "this binary was built without the dashboard; run task ui and rebuild", http.StatusNotFound) }) } files := http.FileServerFS(dist) return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { if strings.HasPrefix(r.URL.Path, "/api/") { httpjson.Error(w, http.StatusNotFound, "no such route") return } if r.Method != http.MethodGet && r.Method != http.MethodHead { w.Header().Set("Allow", "GET, HEAD") http.Error(w, "the dashboard is read-only", http.StatusMethodNotAllowed) return } name := strings.TrimPrefix(r.URL.Path, "/") if name != "" && name != "index.html" && name != page { if info, err := fs.Stat(dist, name); err == nil && !info.IsDir() { if strings.HasPrefix(name, "assets/") { w.Header().Set("Cache-Control", "public, max-age=31536000, immutable") } files.ServeHTTP(w, r) return } } // Every other path is a route inside the SPA. w.Header().Set("Cache-Control", "no-store") http.ServeFileFS(w, r, dist, page) }) }