package server import ( "errors" "io/fs" "mime" "net/http" "os" "path" "path/filepath" "strings" ) // staticHandler serves the built web client with SPA fallback: unknown paths // return index.html so client-side routes survive a page reload. type staticHandler struct { root string } func newStaticHandler(root string) *staticHandler { return &staticHandler{root: root} } func (h *staticHandler) serve(w http.ResponseWriter, r *http.Request) { cleaned := path.Clean("/" + r.URL.Path) rel := strings.TrimPrefix(cleaned, "/") if rel == "" { h.serveIndex(w, r) return } info, err := fs.Stat(os.DirFS(h.root), rel) if err != nil || info.IsDir() { if err != nil && !errors.Is(err, fs.ErrNotExist) { http.Error(w, "internal error", http.StatusInternalServerError) return } h.serveIndex(w, r) return } if contentType := mime.TypeByExtension(filepath.Ext(rel)); contentType != "" { w.Header().Set("Content-Type", contentType) } if strings.HasPrefix(rel, "assets/") { w.Header().Set("Cache-Control", "public, max-age=31536000, immutable") } else { w.Header().Set("Cache-Control", "no-cache") } http.ServeFile(w, r, filepath.Join(h.root, filepath.FromSlash(rel))) } func (h *staticHandler) serveIndex(w http.ResponseWriter, r *http.Request) { index := filepath.Join(h.root, "index.html") if _, err := os.Stat(index); err != nil { writeClientNotBuilt(w) return } w.Header().Set("Content-Type", "text/html; charset=utf-8") w.Header().Set("Cache-Control", "no-cache") http.ServeFile(w, r, index) } func writeClientNotBuilt(w http.ResponseWriter) { w.Header().Set("Content-Type", "text/plain; charset=utf-8") w.WriteHeader(http.StatusServiceUnavailable) _, _ = w.Write([]byte("glchat: web client bundle is not present in this image\n")) }