Merge pull request #1869 from allencloud/fix-cors-bugs

Fix CORS bug #1868
This commit is contained in:
Morgan Bauer 2016-02-25 14:11:31 -08:00
commit 5fc06f746c
2 changed files with 22 additions and 2 deletions

View File

@ -160,7 +160,7 @@ func setupPrimaryRouter(r *mux.Router, context *context, enableCors bool) {
if enableCors {
optionsMethod := "OPTIONS"
localFct = optionsHandler
optionsFct := optionsHandler
wrap := func(w http.ResponseWriter, r *http.Request) {
log.WithFields(log.Fields{"method": optionsMethod, "uri": r.RequestURI}).
@ -169,7 +169,7 @@ func setupPrimaryRouter(r *mux.Router, context *context, enableCors bool) {
writeCorsHeaders(w, r)
}
context.apiVersion = mux.Vars(r)["version"]
localFct(context, w, r)
optionsFct(context, w, r)
}
r.Path("/v{version:[0-9]+.[0-9]+}" + localRoute).

View File

@ -42,6 +42,7 @@ func TestCorsRequest(t *testing.T) {
setupPrimaryRouter(primary, context, true)
w := httptest.NewRecorder()
// test an OPTIONS request when cors enabled
r, e := http.NewRequest("OPTIONS", "/version", nil)
if nil != e {
t.Fatalf("couldn't set up test request")
@ -58,4 +59,23 @@ func TestCorsRequest(t *testing.T) {
if w.Code == 404 {
t.Fatalf("failed not found")
}
// test a normal request ( GET /_ping ) when cors enabled
w2 := httptest.NewRecorder()
r2, e2 := http.NewRequest("GET", "/_ping", nil)
if nil != e2 {
t.Fatalf("couldn't set up test request")
}
primary.ServeHTTP(w2, r2)
if w2.Body.String() != "OK" {
t.Fatalf("couldn't get body content when cors enabled")
}
if w2.Code == 404 {
t.Fatalf("failed not found")
}
}