Skip to content

Commit

Permalink
Merge pull request #69 from vektah/support-options
Browse files Browse the repository at this point in the history
Support OPTIONS requests
  • Loading branch information
vektah authored Mar 28, 2018
2 parents 893ead1 + af38cf0 commit 6129fd2
Show file tree
Hide file tree
Showing 2 changed files with 28 additions and 4 deletions.
17 changes: 13 additions & 4 deletions handler/graphql.go
Original file line number Diff line number Diff line change
Expand Up @@ -60,15 +60,20 @@ func GraphQL(exec graphql.ExecutableSchema, options ...Option) http.HandlerFunc
}

return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if r.Method == http.MethodOptions {
w.Header().Set("Allow", "OPTIONS, GET, POST")
w.WriteHeader(http.StatusOK)
return
}

if strings.Contains(r.Header.Get("Upgrade"), "websocket") {
connectWs(exec, w, r, cfg.upgrader, cfg.recover)
return
}

w.Header().Set("Content-Type", "application/json")

var reqParams params
if r.Method == "GET" {
switch r.Method {
case http.MethodGet:
reqParams.Query = r.URL.Query().Get("query")
reqParams.OperationName = r.URL.Query().Get("operationName")

Expand All @@ -78,12 +83,16 @@ func GraphQL(exec graphql.ExecutableSchema, options ...Option) http.HandlerFunc
return
}
}
} else {
case http.MethodPost:
if err := json.NewDecoder(r.Body).Decode(&reqParams); err != nil {
sendErrorf(w, http.StatusBadRequest, "json body could not be decoded: "+err.Error())
return
}
default:
w.WriteHeader(http.StatusMethodNotAllowed)
return
}
w.Header().Set("Content-Type", "application/json")

doc, qErr := query.Parse(reqParams.Query)
if qErr != nil {
Expand Down
15 changes: 15 additions & 0 deletions handler/graphql_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -65,6 +65,21 @@ func TestHandlerGET(t *testing.T) {
})
}

func TestHandlerOptions(t *testing.T) {
h := GraphQL(&executableSchemaStub{})

resp := doRequest(h, "OPTIONS", "/graphql?query={me{name}}", ``)
assert.Equal(t, http.StatusOK, resp.Code)
assert.Equal(t, "OPTIONS, GET, POST", resp.HeaderMap.Get("Allow"))
}

func TestHandlerHead(t *testing.T) {
h := GraphQL(&executableSchemaStub{})

resp := doRequest(h, "HEAD", "/graphql?query={me{name}}", ``)
assert.Equal(t, http.StatusMethodNotAllowed, resp.Code)
}

func doRequest(handler http.Handler, method string, target string, body string) *httptest.ResponseRecorder {
r := httptest.NewRequest(method, target, strings.NewReader(body))
w := httptest.NewRecorder()
Expand Down

0 comments on commit 6129fd2

Please sign in to comment.