package handlers import ( "net/http" "net/http/httptest" "os" "path/filepath" "testing" "github.com/gin-gonic/gin" ) func TestSPA(t *testing.T) { gin.SetMode(gin.TestMode) dir := t.TempDir() os.MkdirAll(filepath.Join(dir, "assets"), 0o755) os.WriteFile(filepath.Join(dir, "index.html"), []byte("index"), 0o644) os.WriteFile(filepath.Join(dir, "assets", "app-1a2b.js"), []byte("js"), 0o644) os.WriteFile(filepath.Join(dir, "job-capture.user.js"), []byte("userscript"), 0o644) // Outside dir: must never be reachable. os.WriteFile(filepath.Join(filepath.Dir(dir), "secret"), []byte("secret"), 0o644) r := gin.New() r.GET("/jobs/api/health", func(c *gin.Context) { c.String(http.StatusOK, "ok") }) r.NoRoute(SPA(dir, "/jobs")) cases := []struct { method, path string code int body string cache string }{ {"GET", "/jobs/", 200, "index", "no-cache"}, {"GET", "/jobs/leads", 200, "index", "no-cache"}, {"GET", "/jobs/settings/anything", 200, "index", "no-cache"}, {"GET", "/jobs/assets/app-1a2b.js", 200, "js", "public, max-age=31536000, immutable"}, {"GET", "/jobs/job-capture.user.js", 200, "userscript", "no-cache"}, {"GET", "/jobs/api/health", 200, "ok", ""}, {"GET", "/jobs/api/nope", 404, `{"error":"not found"}`, ""}, {"GET", "/jobs/assets/gone.js", 404, "404 page not found", ""}, // net/http refuses a path that climbs, before anything is read. {"GET", "/jobs/../secret", 400, "invalid URL path\n", ""}, {"GET", "/jobs/%2e%2e/secret", 400, "invalid URL path\n", ""}, {"POST", "/jobs/leads", 404, `{"error":"not found"}`, ""}, {"GET", "/elsewhere", 404, `{"error":"not found"}`, ""}, } for _, c := range cases { rec := httptest.NewRecorder() r.ServeHTTP(rec, httptest.NewRequest(c.method, c.path, nil)) if rec.Code != c.code || rec.Body.String() != c.body || rec.Header().Get("Cache-Control") != c.cache { t.Errorf("%s %s = %d %q (cache %q), want %d %q (cache %q)", c.method, c.path, rec.Code, rec.Body, rec.Header().Get("Cache-Control"), c.code, c.body, c.cache) } } rec := httptest.NewRecorder() r.ServeHTTP(rec, httptest.NewRequest("GET", "/jobs", nil)) if rec.Code != http.StatusMovedPermanently || rec.Header().Get("Location") != "/jobs/" { t.Errorf("GET /jobs = %d to %q, want a redirect to /jobs/", rec.Code, rec.Header().Get("Location")) } }