package ginext import ( "net/http" "net/http/httptest" "strings" "testing" "github.com/gin-gonic/gin" ) func TestCorsMiddleware_SetsHeaders(t *testing.T) { rec := httptest.NewRecorder() c, _ := gin.CreateTestContext(rec) c.Request = httptest.NewRequest(http.MethodGet, "/", nil) mw := CorsMiddleware([]string{"X-Foo", "X-Bar"}, []string{"X-Exposed"}) mw(c) h := rec.Header() if h.Get("Access-Control-Allow-Origin") != "*" { t.Fatalf("expected Allow-Origin *") } if h.Get("Access-Control-Allow-Credentials") != "true" { t.Fatalf("expected Allow-Credentials true") } if h.Get("Access-Control-Allow-Headers") != "X-Foo, X-Bar" { t.Fatalf("expected Allow-Headers X-Foo, X-Bar got %q", h.Get("Access-Control-Allow-Headers")) } if h.Get("Access-Control-Expose-Headers") != "X-Exposed" { t.Fatalf("expected Expose-Headers X-Exposed got %q", h.Get("Access-Control-Expose-Headers")) } allowMethods := h.Get("Access-Control-Allow-Methods") for _, want := range []string{"OPTIONS", "GET", "POST", "PUT", "PATCH", "DELETE", "COUNT"} { if !strings.Contains(allowMethods, want) { t.Errorf("expected Allow-Methods to contain %q, got %q", want, allowMethods) } } } func TestCorsMiddleware_NoExposeHeader(t *testing.T) { rec := httptest.NewRecorder() c, _ := gin.CreateTestContext(rec) c.Request = httptest.NewRequest(http.MethodGet, "/", nil) mw := CorsMiddleware([]string{"X-Foo"}, []string{}) mw(c) if _, ok := rec.Header()["Access-Control-Expose-Headers"]; ok { t.Fatalf("expected Expose-Headers to be unset when empty") } } func TestCorsMiddleware_OptionsAborts(t *testing.T) { rec := httptest.NewRecorder() c, _ := gin.CreateTestContext(rec) c.Request = httptest.NewRequest(http.MethodOptions, "/", nil) mw := CorsMiddleware([]string{"X-Foo"}, nil) mw(c) if !c.IsAborted() { t.Fatalf("expected context aborted on OPTIONS") } if rec.Code != http.StatusOK { t.Fatalf("expected 200 on OPTIONS, got %d", rec.Code) } } func TestCorsMiddleware_NonOptionsContinues(t *testing.T) { rec := httptest.NewRecorder() c, _ := gin.CreateTestContext(rec) c.Request = httptest.NewRequest(http.MethodGet, "/", nil) mw := CorsMiddleware([]string{"X-Foo"}, nil) mw(c) if c.IsAborted() { t.Fatalf("non-OPTIONS request should not be aborted") } }