Files
archie/modules/dashboard/dashboard.go
T
sam 18d1e07a21 fix(dashboard): one pattern serves the page and the API catch-all (archie #2005)
The dashboard registered "/api/" and then "GET /", which ServeMux refuses:
"GET /" names fewer methods than "/api/" but a more general path, so a binary
with the dashboard built in panicked on start. Staging went down on the deploy
that first shipped both.

One handler behind one pattern decides instead: an unclaimed /api/ path is a
JSON 404, the page is read-only, and everything else is a route inside the SPA.

The test reproduces the panic against the old routing, and pins what each path
answers.
2026-11-16 00:05:02 +11:00

62 lines
2.0 KiB
Go

// 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)
})
}