Skip to content

Commit

Permalink
Merge pull request #174 from resgateio/feature/gh-171-cors-access-con…
Browse files Browse the repository at this point in the history
…trol-allow-headers

Feature/gh 171 cors access control allow headers
  • Loading branch information
jirenius committed Sep 10, 2020
2 parents 4a02ef3 + 11e9a0b commit 3811991
Show file tree
Hide file tree
Showing 2 changed files with 33 additions and 0 deletions.
4 changes: 4 additions & 0 deletions server/apiHandler.go
Expand Up @@ -57,6 +57,10 @@ func (s *Service) apiHandler(w http.ResponseWriter, r *http.Request) {
err := s.setCommonHeaders(w, r)
if r.Method == "OPTIONS" {
w.Header().Set("Access-Control-Allow-Methods", s.cfg.allowMethods)
reqHeaders := r.Header["Access-Control-Request-Headers"]
if len(reqHeaders) > 0 {
w.Header().Set("Access-Control-Allow-Headers", strings.Join(reqHeaders, ", "))
}
return
}
if err != nil {
Expand Down
29 changes: 29 additions & 0 deletions test/21http_options_test.go
Expand Up @@ -42,3 +42,32 @@ func TestHTTPOptions_AllowOrigin_ExpectedResponseHeaders(t *testing.T) {
})
}
}

func TestHTTPOptions_RequestHeaders_ExpectedResponseHeaders(t *testing.T) {
tbl := []struct {
RequestHeaders []string // Request's Origin header. Empty means no Origin header.
ExpectedHeaders map[string]string // Expected response Headers
ExpectedMissingHeaders []string // Expected response headers not to be included
}{
{[]string{"Content-Type"}, map[string]string{"Access-Control-Allow-Headers": "Content-Type"}, nil},
{[]string{"X-PINGOTHER", "Content-Type"}, map[string]string{"Access-Control-Allow-Headers": "X-PINGOTHER, Content-Type"}, nil},
{[]string{"X-PINGOTHER", "Content-Type", "Authorization"}, map[string]string{"Access-Control-Allow-Headers": "X-PINGOTHER, Content-Type, Authorization"}, nil},
{nil, nil, []string{"Access-Control-Allow-Headers"}},
}

for i, l := range tbl {
l := l
runNamedTest(t, fmt.Sprintf("#%d", i+1), func(s *Session) {
hreq := s.HTTPRequest("OPTIONS", "/api/test/model", nil, func(req *http.Request) {
if len(l.RequestHeaders) > 0 {
req.Header["Access-Control-Request-Headers"] = l.RequestHeaders
}
})
// Validate http response
hreq.GetResponse(t).
Equals(t, http.StatusOK, nil).
AssertHeaders(t, l.ExpectedHeaders).
AssertMissingHeaders(t, l.ExpectedMissingHeaders)
})
}
}

0 comments on commit 3811991

Please sign in to comment.