Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Using alternative contexts #12

Closed
wants to merge 3 commits into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
42 changes: 42 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
24 changes: 23 additions & 1 deletion handler.go
Original file line number Diff line number Diff line change
Expand Up @@ -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"`
Expand Down Expand Up @@ -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 {
Expand Down