Skip to content

fix(middleware): only short-circuit CORS preflights - #3064

Open
deepakganesh78 wants to merge 1 commit into
labstack:v4from
deepakganesh78:fix/issue2534-cors-preflight
Open

fix(middleware): only short-circuit CORS preflights#3064
deepakganesh78 wants to merge 1 commit into
labstack:v4from
deepakganesh78:fix/issue2534-cors-preflight

Conversation

@deepakganesh78

@deepakganesh78 deepakganesh78 commented Aug 2, 2026

Copy link
Copy Markdown

Fixes #2534.

Reproduction

Echo v4 CORS middleware treated every OPTIONS request as a preflight, so both OPTIONS /hello without Origin and OPTIONS /hello with Origin but without Access-Control-Request-Method short-circuited before a registered OPTIONS handler could run. Added TestCORS_NonPreflightOPTIONSPassThrough, which fails against the old implementation.

Root cause

The middleware used req.Method == http.MethodOptions as its preflight test. Per Fetch, a CORS preflight is an OPTIONS request with both Origin and Access-Control-Request-Method.

Fix

Classify preflights with method + Origin + Access-Control-Request-Method. Non-preflight OPTIONS requests now continue through the handler chain while true preflights keep the existing 204 short-circuit and CORS headers.

Compatibility / behavior change

This intentionally changes non-preflight OPTIONS handling. In addition to OPTIONS requests with Origin but no Access-Control-Request-Method, OPTIONS requests with no Origin now call next(c) instead of being answered directly by CORS with 204 No Content. That is correct because those requests are not CORS preflights, but apps with auth or other middleware in front of non-preflight OPTIONS routes may now see that middleware run.

Validation

  • go test ./middleware -run TestCORS_NonPreflightOPTIONSPassThrough -count=1 fails with middleware/cors.go reverted.
  • go test ./middleware -run "CORS|CorsHeaders|allowOrigin" -count=1 passes.
  • gofmt -l . prints bind_test.go only; that file is pre-existing unformatted and is intentionally not touched by this PR.
  • go vet ./... passes.
  • go build ./... passes.
  • go test ./... passes.

AI-assisted with GitHub Copilot CLI.

Treat OPTIONS requests as CORS preflights only when Origin and Access-Control-Request-Method are present, so non-preflight OPTIONS handlers can run.

Fixes labstack#2534

Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
@deepakganesh78
deepakganesh78 force-pushed the fix/issue2534-cors-preflight branch from 4839536 to ecd917d Compare August 2, 2026 15:39
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant