@@ -54,12 +54,12 @@ func formatErrorsWithCode(data map[string]interface{}, err error, code string) m
54
54
// a single object with { query, variables, operationName } or a list
55
55
// of that object.
56
56
func (g * Gateway ) GraphQLHandler (w http.ResponseWriter , r * http.Request ) {
57
- operations , batchMode , payloadErr := parseRequest (r )
57
+ operations , batchMode , parseStatusCode , payloadErr := parseRequest (r )
58
58
59
59
// if there was an error retrieving the payload
60
60
if payloadErr != nil {
61
61
response := formatErrors (payloadErr )
62
- w .WriteHeader (http . StatusUnprocessableEntity )
62
+ w .WriteHeader (parseStatusCode )
63
63
err := json .NewEncoder (w ).Encode (response )
64
64
if err != nil {
65
65
g .logger .Warn ("Failed to encode error response:" , err .Error ())
@@ -165,26 +165,24 @@ func (g *Gateway) GraphQLHandler(w http.ResponseWriter, r *http.Request) {
165
165
emitResponse (w , statusCode , string (response ))
166
166
}
167
167
168
- // Parses request to operations (single or batch mode)
169
- func parseRequest (r * http.Request ) (operations []* HTTPOperation , batchMode bool , payloadErr error ) {
168
+ // Parses request to operations (single or batch mode).
169
+ // Returns an error and an error status code if the request is invalid.
170
+ func parseRequest (r * http.Request ) (operations []* HTTPOperation , batchMode bool , errStatusCode int , payloadErr error ) {
170
171
// this handler can handle multiple operations sent in the same query. Internally,
171
- // it modules a single operation as a list of one.
172
+ // it models a single operation as a list of one.
172
173
operations = []* HTTPOperation {}
173
-
174
- // the error we have encountered when extracting query input
175
-
176
- // make our lives easier. track if we're in batch mode
177
- batchMode = false
178
-
179
- if r .Method == http .MethodGet {
180
- // if we got a GET request
174
+ switch r .Method {
175
+ case http .MethodGet :
181
176
operations , payloadErr = parseGetRequest (r )
182
-
183
- } else if r .Method == http .MethodPost {
184
- // or we got a POST request
177
+ case http .MethodPost :
185
178
operations , batchMode , payloadErr = parsePostRequest (r )
179
+ default :
180
+ errStatusCode = http .StatusMethodNotAllowed
181
+ payloadErr = errors .New (http .StatusText (http .StatusMethodNotAllowed ))
182
+ }
183
+ if errStatusCode == 0 && payloadErr != nil { // ensure an error always results in a failed status code
184
+ errStatusCode = http .StatusUnprocessableEntity
186
185
}
187
-
188
186
return
189
187
}
190
188
0 commit comments