Skip to content

Commit

Permalink
[bugfix] Handle CORS pre-flight request in middleware (#112)
Browse files Browse the repository at this point in the history
  • Loading branch information
matiasanaya authored and elithrar committed May 8, 2018
1 parent 2b8556b commit 13a38d2
Show file tree
Hide file tree
Showing 2 changed files with 22 additions and 1 deletion.
5 changes: 4 additions & 1 deletion cors.go
Original file line number Diff line number Diff line change
Expand Up @@ -48,7 +48,10 @@ const (
func (ch *cors) ServeHTTP(w http.ResponseWriter, r *http.Request) {
origin := r.Header.Get(corsOriginHeader)
if !ch.isOriginAllowed(origin) {
ch.h.ServeHTTP(w, r)
if r.Method != corsOptionMethod || ch.ignoreOptions {
ch.h.ServeHTTP(w, r)
}

return
}

Expand Down
18 changes: 18 additions & 0 deletions cors_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -122,6 +122,24 @@ func TestCORSHandlerOptionsRequestMustNotBePassedToNextHandler(t *testing.T) {
}
}

func TestCORSHandlerOptionsRequestMustNotBePassedToNextHandlerWhenOriginNotAllowed(t *testing.T) {
r := newRequest("OPTIONS", "http://www.example.com/")
r.Header.Set("Origin", r.URL.String())
r.Header.Set(corsRequestMethodHeader, "GET")

rr := httptest.NewRecorder()

testHandler := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
t.Fatal("Options request must not be passed to next handler")
})

CORS(AllowedOrigins([]string{}))(testHandler).ServeHTTP(rr, r)

if status := rr.Code; status != http.StatusOK {
t.Fatalf("bad status: got %v want %v", status, http.StatusOK)
}
}

func TestCORSHandlerAllowedMethodForPreflight(t *testing.T) {
r := newRequest("OPTIONS", "http://www.example.com/")
r.Header.Set("Origin", r.URL.String())
Expand Down

0 comments on commit 13a38d2

Please sign in to comment.