Skip to content

Commit

Permalink
CORS: skip preflight if route is RouteNotFound
Browse files Browse the repository at this point in the history
  • Loading branch information
System-Glitch committed May 17, 2024
1 parent d3f977d commit 2234637
Show file tree
Hide file tree
Showing 2 changed files with 21 additions and 1 deletion.
2 changes: 1 addition & 1 deletion middleware.go
Original file line number Diff line number Diff line change
Expand Up @@ -226,7 +226,7 @@ func (m *corsMiddleware) Handle(next Handler) Handler {

options.ConfigureCommon(headers, requestHeaders)

if request.Method() == http.MethodOptions {
if request.Method() == http.MethodOptions && request.Route.GetName() != RouteNotFound {
options.HandlePreflight(headers, requestHeaders)
if options.OptionsPassthrough {
next(response, request)
Expand Down
20 changes: 20 additions & 0 deletions middleware_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -555,6 +555,7 @@ func TestCORSMiddleware(t *testing.T) {
options func() *cors.Options
req func() *Request
expectedHeaders http.Header
routeName string
desc string
respBody string
expectedBody string
Expand Down Expand Up @@ -593,6 +594,24 @@ func TestCORSMiddleware(t *testing.T) {
"Access-Control-Max-Age": []string{"43200"},
},
},
{
desc: "preflight_not_found",
options: cors.Default,
routeName: RouteNotFound,
req: func() *Request {
req := NewRequest(httptest.NewRequest(http.MethodOptions, "/test", nil))
req.Header().Set("Origin", "https://google.com")
req.Header().Set("Access-Control-Request-Method", http.MethodGet)
return req
},
respStatus: http.StatusNotFound,
respBody: "",
expectedStatusCode: http.StatusNotFound,
expectedBody: "",
expectedHeaders: http.Header{
"Access-Control-Allow-Origin": []string{"*"},
},
},
{
desc: "preflight_passthrough",
options: func() *cors.Options {
Expand Down Expand Up @@ -661,6 +680,7 @@ func TestCORSMiddleware(t *testing.T) {
Meta: map[string]any{
MetaCORS: c.options(),
},
name: c.routeName,
}
recorder := httptest.NewRecorder()
response := NewResponse(nil, request, recorder)
Expand Down

0 comments on commit 2234637

Please sign in to comment.