Skip to content

Commit

Permalink
Add AllowedMethods field to transport.Options
Browse files Browse the repository at this point in the history
to enable users to specify allowed HTTP methods.
  • Loading branch information
morikuni committed Apr 4, 2022
1 parent 12b0b38 commit 4d92788
Show file tree
Hide file tree
Showing 2 changed files with 29 additions and 7 deletions.
14 changes: 12 additions & 2 deletions graphql/handler/transport/options.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,12 +2,15 @@ package transport

import (
"net/http"
"strings"

"github.com/99designs/gqlgen/graphql"
)

// Options responds to http OPTIONS and HEAD requests
type Options struct{}
type Options struct {
AllowedMethods []string
}

var _ graphql.Transport = Options{}

Expand All @@ -18,9 +21,16 @@ func (o Options) Supports(r *http.Request) bool {
func (o Options) Do(w http.ResponseWriter, r *http.Request, exec graphql.GraphExecutor) {
switch r.Method {
case http.MethodOptions:
w.Header().Set("Allow", "OPTIONS, GET, POST")
w.Header().Set("Allow", o.allowedMethods())
w.WriteHeader(http.StatusOK)
case http.MethodHead:
w.WriteHeader(http.StatusMethodNotAllowed)
}
}

func (o Options) allowedMethods() string {
if o.AllowedMethods == nil {
return "OPTIONS, GET, POST"
}
return strings.Join(o.AllowedMethods, ", ")
}
22 changes: 17 additions & 5 deletions graphql/handler/transport/options_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,22 +4,34 @@ import (
"net/http"
"testing"

"github.com/stretchr/testify/assert"

"github.com/99designs/gqlgen/graphql/handler/testserver"
"github.com/99designs/gqlgen/graphql/handler/transport"
"github.com/stretchr/testify/assert"
)

func TestOptions(t *testing.T) {
h := testserver.New()
h.AddTransport(transport.Options{})

t.Run("responds to options requests", func(t *testing.T) {
t.Run("responds to options requests with default methods", func(t *testing.T) {
h := testserver.New()
h.AddTransport(transport.Options{})
resp := doRequest(h, "OPTIONS", "/graphql?query={me{name}}", ``)
assert.Equal(t, http.StatusOK, resp.Code)
assert.Equal(t, "OPTIONS, GET, POST", resp.Header().Get("Allow"))
})

t.Run("responds to options requests with specified methods", func(t *testing.T) {
h := testserver.New()
h.AddTransport(transport.Options{
AllowedMethods: []string{http.MethodOptions, http.MethodPost, http.MethodHead},
})
resp := doRequest(h, "OPTIONS", "/graphql?query={me{name}}", ``)
assert.Equal(t, http.StatusOK, resp.Code)
assert.Equal(t, "OPTIONS, POST, HEAD", resp.Header().Get("Allow"))
})

t.Run("responds to head requests", func(t *testing.T) {
h := testserver.New()
h.AddTransport(transport.Options{})
resp := doRequest(h, "HEAD", "/graphql?query={me{name}}", ``)
assert.Equal(t, http.StatusMethodNotAllowed, resp.Code)
})
Expand Down

0 comments on commit 4d92788

Please sign in to comment.