Serving over HTTP
This page shows how to serve a schema over HTTP: with a handler of your own,
which fits any router or framework, or with the ready-made
gql-go/handler package. The
complete program serves a schema with a handler of its own
and authentication middleware.
A handler of your own
A GraphQL request over HTTP is usually a POST whose JSON body holds query,
operationName and variables. A handler decodes it, runs graphql.Do with
the request’s context, and writes the result as JSON:
// GraphQLHandler serves schema over HTTP: it accepts POST requests with a
// JSON body and answers with the result as JSON.
func GraphQLHandler(schema graphql.Schema) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if r.Method != http.MethodPost {
w.Header().Set("Allow", http.MethodPost)
writeErrors(w, http.StatusMethodNotAllowed, "GraphQL requests must use POST.")
return
}
// Browsers send a JSON body to another site only after a CORS
// preflight, so requiring it also keeps out forms from other sites.
if mt, _, _ := mime.ParseMediaType(r.Header.Get("Content-Type")); mt != "application/json" {
writeErrors(w, http.StatusUnsupportedMediaType, "GraphQL requests must be application/json.")
return
}
// A pointer, so that a body of null is told apart from an object.
var req *request
dec := json.NewDecoder(http.MaxBytesReader(w, r.Body, maxBodyBytes))
if err := dec.Decode(&req); err != nil {
writeErrors(w, http.StatusBadRequest, "The request body is not valid JSON: "+err.Error())
return
}
if err := dec.Decode(&struct{}{}); req == nil || err != io.EOF {
writeErrors(w, http.StatusBadRequest, "The request body must hold a single JSON object.")
return
}
result := graphql.Do(graphql.Params{
Schema: schema,
RequestString: req.Query,
OperationName: req.OperationName,
VariableValues: req.Variables,
// Resolvers see the request's context: its values, such as the
// signed-in user, and its cancellation when the client leaves.
Context: r.Context(),
})
writeJSON(w, http.StatusOK, result)
})
}Choices this handler makes, which you can change to suit your API:
- Only
POST. The GraphQL over HTTP specification allowsGETtoo, for queries only. AcceptingPOSTalone is the simplest choice that follows it; other methods get405with anAllowheader. - Only
application/json. Browsers send a JSON body to another site only after a CORS preflight, which the server can refuse. A form or plain text body needs no preflight, so with cookie authentication another site could make a signed-in user’s browser send one; requiring JSON keeps those out, and other types get415. Applications that authenticate with cookies still need a CSRF defense for anything else they accept, and a strict CORS policy. - A bounded body, holding one JSON object.
http.MaxBytesReaderstops reading after 1 MiB, so a client cannot make the server read without limit, and anything after the first JSON value is rejected. - Status codes. A body that cannot be read gets
400. A request that reachesgraphql.Dogets200, even when the result has errors, which is what clients of theapplication/jsonmedia type expect;dataanderrorstell what happened.
The result encodes with encoding/json as it is. To change errors before they
are sent, such as hiding internal details, see
Masking internal errors.
Any router or framework
The handler is an http.Handler, so it mounts in the standard library’s
http.ServeMux, and in any router that accepts one:
mux := http.NewServeMux()
mux.Handle("/graphql", WithUser(GraphQLHandler(schema)))
log.Fatal(http.ListenAndServe(":8080", mux))Web frameworks that have their own handler type provide a way to mount an
http.Handler, or give access to the underlying *http.Request and
http.ResponseWriter, which is all the handler needs. When a framework keeps
request values in its own context type, copy what resolvers need into the
request’s context.Context before calling graphql.Do.
The request context
graphql.Do gets r.Context(), so resolvers see the values that middleware
added to the request, and execution stops waiting when the client goes away.
Authentication middleware is the usual place to find the user:
// WithUser is authentication middleware: it puts the user named in the
// X-User header in the request's context. Real code checks a token.
func WithUser(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if name := r.Header.Get("X-User"); name != "" {
r = r.WithContext(context.WithValue(r.Context(), userKey{}, name))
}
next.ServeHTTP(w, r)
})
}Resolvers then read the user from p.Context, as described in
Context.
Doing more per request
The handler is the place to add work around execution:
- Caching the parsed and validated document of repeated queries, with
PlanCache. - Validation rules of your own, such as a depth limit, by running the parse, validate and execute steps yourself, as in Adding rules.
- Tracing and metrics, with extensions.
gql-go/handler
gql-go/handler is a ready-made
http.Handler, with the in-browser GraphiQL editor:
h := handler.New(&handler.Config{
Schema: &schema,
Pretty: true,
GraphiQL: true,
})
mux.Handle("/graphql", h)v0.4.1 and v0.3.2, mutations run only from a POST with an
application/json or application/graphql body; other requests that select a
mutation get 405 (GET) or 415 without executing it. Earlier versions ran
them from any request form, which allowed cross-site request forgery with
cookie authentication
(GHSA-4gfj-j6mf-x2mh).
Upgrade, and send mutations as POST with JSON.It reads the request in any of these forms, with the operation in the URL taking precedence over the body:
| Request | Read from |
|---|---|
GET | query, variables (JSON) and operationName in the URL |
POST, application/json | the JSON body; variables can also be a JSON string |
POST, application/graphql | the body, as the query |
POST, application/x-www-form-urlencoded | the form fields, like GET |
Queries run from any of them; mutations only from the two POST forms that
need a CORS preflight. The handler answers with 200 and the result as JSON,
except for those rejected mutations. A body that cannot be read
reaches graphql.Do as an empty request, so the response says
Must provide an operation. instead of describing the problem. Responses with
the status codes and media type of the GraphQL over HTTP specification are
planned (gql-go/handler#4).
| Option | Effect |
|---|---|
Pretty | Indents the JSON response. |
GraphiQL | Serves GraphiQL to browsers, which send Accept: text/html; its scripts load from a CDN. |
Playground, PlaygroundConfig | Serves GraphQL Playground instead. |
RootObjectFn | Builds the root value from the request. The handler has already read the body, so r.Body is empty unless RestoreRequestBody is set; the fields of a form body are in r.FormValue. |
RestoreRequestBody | Leaves r.Body readable from the start after the handler has read a JSON or application/graphql body, for RootObjectFn and the code around the handler. It is restored once: a reader that consumes it, such as RootObjectFn, leaves it empty for the next unless it restores it in turn. A form body is still consumed (v0.5.0). |
FormatErrorFn | Replaces each error with the one it returns. It receives an error: for errors in the document and in resolvers, a *gqlerrors.Error with Locations, Path and, for resolvers, OriginalError; other errors, such as an empty request, are plain errors, so use errors.As rather than a type assertion. The location and path reach the client only if the function copies them. |
ResultCallbackFn | Called after a JSON response is written, with the request’s params, the result and the encoded body; not when GraphiQL or Playground is served. For a rejected mutation, params.RootObject is nil, since RootObjectFn does not run (v0.4.2, v0.3.3). |
handler.NewConfig() returns a configuration with Pretty and GraphiQL on;
a Config literal starts with both off. Turn GraphiQL off where the schema
should not be browsable, such as in production, and bound the body size by
wrapping the handler, for example with http.MaxBytesHandler(h, 1<<20); a body
over the limit gets an error response. The limit applies to the body only: a
request with the operation in its URL is read from there, whatever its body.
ServeHTTP passes r.Context() to graphql.Do; ContextHandler(ctx, w, r)
takes the context from you instead.
To keep your own handler and use only the request reading,
handler.NewRequestOptions(r) returns the query, variables and operation name
from any of the forms above. It does not report errors: a request it cannot read
gives empty options. It does not check the method or content type either, so a
server that executes the options itself must apply the same rule as the
handler: run mutations only from a POST with an application/json or
application/graphql body.
Not covered yet
Subscriptions need a WebSocket or server-sent events transport, which neither
the library nor gql-go/handler provides yet; see
Serving subscriptions
and gql-go/handler#4. File uploads
with multipart requests are planned in
gql-go/handler#15.
Complete program
main.go
package main
import (
"context"
"encoding/json"
"errors"
"fmt"
"io"
"log"
"mime"
"net/http"
"net/http/httptest"
"strings"
"github.com/gql-go/graphql"
"github.com/gql-go/graphql/gqlerrors"
)
// maxBodyBytes bounds the size of a request body.
const maxBodyBytes = 1 << 20
// request is the body of a GraphQL request over HTTP.
type request struct {
Query string `json:"query"`
OperationName string `json:"operationName"`
Variables map[string]interface{} `json:"variables"`
}
// GraphQLHandler serves schema over HTTP: it accepts POST requests with a
// JSON body and answers with the result as JSON.
func GraphQLHandler(schema graphql.Schema) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if r.Method != http.MethodPost {
w.Header().Set("Allow", http.MethodPost)
writeErrors(w, http.StatusMethodNotAllowed, "GraphQL requests must use POST.")
return
}
// Browsers send a JSON body to another site only after a CORS
// preflight, so requiring it also keeps out forms from other sites.
if mt, _, _ := mime.ParseMediaType(r.Header.Get("Content-Type")); mt != "application/json" {
writeErrors(w, http.StatusUnsupportedMediaType, "GraphQL requests must be application/json.")
return
}
// A pointer, so that a body of null is told apart from an object.
var req *request
dec := json.NewDecoder(http.MaxBytesReader(w, r.Body, maxBodyBytes))
if err := dec.Decode(&req); err != nil {
writeErrors(w, http.StatusBadRequest, "The request body is not valid JSON: "+err.Error())
return
}
if err := dec.Decode(&struct{}{}); req == nil || err != io.EOF {
writeErrors(w, http.StatusBadRequest, "The request body must hold a single JSON object.")
return
}
result := graphql.Do(graphql.Params{
Schema: schema,
RequestString: req.Query,
OperationName: req.OperationName,
VariableValues: req.Variables,
// Resolvers see the request's context: its values, such as the
// signed-in user, and its cancellation when the client leaves.
Context: r.Context(),
})
writeJSON(w, http.StatusOK, result)
})
}
func writeErrors(w http.ResponseWriter, status int, message string) {
writeJSON(w, status, &graphql.Result{
Errors: []gqlerrors.FormattedError{gqlerrors.NewFormattedError(message)},
})
}
func writeJSON(w http.ResponseWriter, status int, v interface{}) {
w.Header().Set("Content-Type", "application/json; charset=utf-8")
w.WriteHeader(status)
if err := json.NewEncoder(w).Encode(v); err != nil {
log.Printf("writing response: %v", err)
}
}
type userKey struct{}
// WithUser is authentication middleware: it puts the user named in the
// X-User header in the request's context. Real code checks a token.
func WithUser(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if name := r.Header.Get("X-User"); name != "" {
r = r.WithContext(context.WithValue(r.Context(), userKey{}, name))
}
next.ServeHTTP(w, r)
})
}
func newSchema() (graphql.Schema, error) {
return graphql.NewSchema(graphql.SchemaConfig{
Query: graphql.NewObject(graphql.ObjectConfig{
Name: "Query",
Fields: graphql.Fields{
"me": &graphql.Field{
Type: graphql.String,
Resolve: func(p graphql.ResolveParams) (interface{}, error) {
name, ok := p.Context.Value(userKey{}).(string)
if !ok {
return nil, errors.New("not signed in")
}
return name, nil
},
},
},
}),
})
}
func main() {
schema, err := newSchema()
if err != nil {
log.Fatal(err)
}
mux := http.NewServeMux()
mux.Handle("/graphql", WithUser(GraphQLHandler(schema)))
// A real server would call http.ListenAndServe(":8080", mux).
send := func(method, contentType, body, user string) {
r := httptest.NewRequest(method, "/graphql", strings.NewReader(body))
r.Header.Set("Content-Type", contentType)
if user != "" {
r.Header.Set("X-User", user)
}
w := httptest.NewRecorder()
mux.ServeHTTP(w, r)
out, _ := io.ReadAll(w.Body)
fmt.Printf("%s %d %s", method, w.Code, out)
}
const typeJSON = "application/json"
send("POST", typeJSON, `{"query":"{ me }"}`, "ged")
send("POST", typeJSON, `{"query":"{ me }"}`, "")
send("POST", typeJSON, `{"query":`, "ged")
send("POST", "text/plain", `{"query":"{ me }"}`, "ged")
send("GET", "", ``, "ged")
}The program serves the schema with GraphQLHandler behind WithUser, and sends
five requests through it with httptest: a signed-in query, an anonymous one,
a body that is not valid JSON, a plain text body, and a GET:
POST 200 {"data":{"me":"ged"}}
POST 200 {"data":{"me":null},"errors":[{"message":"not signed in","locations":[{"line":1,"column":3}],"path":["me"]}]}
POST 400 {"data":null,"errors":[{"message":"The request body is not valid JSON: unexpected EOF","locations":[]}]}
POST 415 {"data":null,"errors":[{"message":"GraphQL requests must be application/json.","locations":[]}]}
GET 405 {"data":null,"errors":[{"message":"GraphQL requests must use POST.","locations":[]}]}