| 59 | } |
| 60 | |
| 61 | func (h *Handler) ServeHTTP(w http.ResponseWriter, r *http.Request) { |
| 62 | // Clean URL path |
| 63 | p := path.Clean(r.URL.Path) |
| 64 | if p == "." { |
| 65 | p = "" |
| 66 | } |
| 67 | p = strings.TrimPrefix(p, "/") |
| 68 | |
| 69 | // API paths must be handled by registered routes; do not fall through to SPA. |
| 70 | // If we're here it means no route matched — return 404 instead of serving |
| 71 | // index.html (which would be misinterpreted as a 200 success by API clients). |
| 72 | if strings.HasPrefix(r.URL.Path, "/v1/") || strings.HasPrefix(r.URL.Path, "/api/") { |
| 73 | http.NotFound(w, r) |
| 74 | return |
| 75 | } |
| 76 | |
| 77 | // Try to open the file if the path has an extension (static asset) |
| 78 | if p != "" && filepath.Ext(p) != "" { |
| 79 | f, err := h.fsys.Open(p) |
| 80 | if err == nil { |
| 81 | defer f.Close() |
| 82 | stat, _ := f.Stat() |
| 83 | if stat != nil && !stat.IsDir() { |
| 84 | ct := mime.TypeByExtension(filepath.Ext(p)) |
| 85 | if ct != "" { |
| 86 | w.Header().Set("Content-Type", ct) |
| 87 | } |
| 88 | // Cache static assets aggressively (they have content hashes) |
| 89 | if p != "index.html" { |
| 90 | w.Header().Set("Cache-Control", "public, max-age=31536000, immutable") |
| 91 | } |
| 92 | serve(w, r, f) |
| 93 | return |
| 94 | } |
| 95 | } |
| 96 | } |
| 97 | |
| 98 | // Fallback: serve index.html for SPA client-side routing (GET/HEAD only) |
| 99 | if r.Method != http.MethodGet && r.Method != http.MethodHead { |
| 100 | http.Error(w, "method not allowed", http.StatusMethodNotAllowed) |
| 101 | return |
| 102 | } |
| 103 | w.Header().Set("Content-Type", "text/html; charset=utf-8") |
| 104 | w.Header().Set("Cache-Control", "no-cache") |
| 105 | serve(w, r, strings.NewReader(string(h.index))) |
| 106 | } |