diff --git a/README.md b/README.md index 96cc881..d34ee08 100644 --- a/README.md +++ b/README.md @@ -32,6 +32,48 @@ func main() { } ``` +By default, `context.Background()` is used to generate contexts. If you need to provide an alternative method to support environments, like AppEngine, you can provide a RequestContextGenerator. + +```go +package main + +import ( + "net/http" + + "golang.org/x/net/context" + "github.com/graphql-go/handler" + "google.golang.org/appengine" +) + +type contextGenerator struct { + +} + +func (cg *contextGenerator) MakeContext(w http.ResponseWriter, r *http.Request) (context.Context, error) { + ctx := appengine.NewContext(r) + + return ctx, nil +} + +func main() { + + // define GraphQL schema using relay library helpers + schema := graphql.NewSchema(...) + + h := handler.New(&handler.Config{ + Schema: schema, + Pretty: true, + }) + + cg := &contextGenerator{} + h.SetRequestContextGenerator(cg) + + // serve HTTP + http.Handle("/graphql", h) + http.ListenAndServe(":8080", nil) +} +``` + ### Details The handler will accept requests with diff --git a/handler.go b/handler.go index 96483a8..d4003f1 100644 --- a/handler.go +++ b/handler.go @@ -21,8 +21,10 @@ const ( type Handler struct { Schema *graphql.Schema + rcg RequestContextGenerator pretty bool } + type RequestOptions struct { Query string `json:"query" url:"query" schema:"query"` Variables map[string]interface{} `json:"variables" url:"variables" schema:"variables"` @@ -143,9 +145,29 @@ func (h *Handler) ContextHandler(ctx context.Context, w http.ResponseWriter, r * } } +type RequestContextGenerator interface { + MakeContext(w http.ResponseWriter, r *http.Request) (context.Context, error) +} + +func (h *Handler) SetRequestContextGenerator(rcg RequestContextGenerator) { + h.rcg = rcg +} + +func (h *Handler) GetContext(w http.ResponseWriter, r *http.Request) (ctx context.Context, err error) { + if h.rcg != nil { + return h.rcg.MakeContext(w, r) + } else { + return context.Background(), nil + } +} + // ServeHTTP provides an entrypoint into executing graphQL queries. func (h *Handler) ServeHTTP(w http.ResponseWriter, r *http.Request) { - h.ContextHandler(context.Background(), w, r) + if ctx, err := h.GetContext(w, r); err != nil { + panic(err) + } else { + h.ContextHandler(ctx, w, r) + } } type Config struct {