package main import ( "net/http" "net/http/httptest" "testing" "testing/fstest" "github.com/gin-gonic/gin" ) func TestAPIAndFrontendShareRouter(t *testing.T) { gin.SetMode(gin.TestMode) router := gin.New() router.GET("/api/ping", func(c *gin.Context) { c.JSON(http.StatusOK, gin.H{"status": "ok"}) }) router.NoRoute(serveFrontend(fstest.MapFS{ "index.html": {Data: []byte("app")}, "assets/app.js": {Data: []byte("console.log('app')")}, })) tests := []struct { path string statusCode int body string }{ {path: "/api/ping", statusCode: http.StatusOK, body: `{"status":"ok"}`}, {path: "/admin", statusCode: http.StatusOK, body: "app"}, {path: "/assets/app.js", statusCode: http.StatusOK, body: "console.log('app')"}, {path: "/api/missing", statusCode: http.StatusNotFound, body: "404 page not found"}, {path: "/uploads/missing.png", statusCode: http.StatusNotFound, body: "404 page not found"}, } for _, test := range tests { t.Run(test.path, func(t *testing.T) { recorder := httptest.NewRecorder() router.ServeHTTP(recorder, httptest.NewRequest(http.MethodGet, test.path, nil)) if recorder.Code != test.statusCode || recorder.Body.String() != test.body { t.Fatalf("unexpected response: status=%d body=%q", recorder.Code, recorder.Body.String()) } }) } } func TestCORSMiddlewareUsesServicePort(t *testing.T) { gin.SetMode(gin.TestMode) router := gin.New() router.Use(corsMiddleware("8080")) router.GET("/api/ping", func(c *gin.Context) { c.Status(http.StatusNoContent) }) recorder := httptest.NewRecorder() request := httptest.NewRequest(http.MethodGet, "/api/ping", nil) request.Header.Set("Origin", "http://localhost:8080") router.ServeHTTP(recorder, request) if origin := recorder.Header().Get("Access-Control-Allow-Origin"); origin != "http://localhost:8080" { t.Fatalf("unexpected allowed origin: %q", origin) } }