-
Notifications
You must be signed in to change notification settings - Fork 20
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
Handler.go #24
Open
unreadable
wants to merge
1
commit into
playlyfe:master
Choose a base branch
from
unreadable:patch-1
base: master
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Handler.go #24
Changes from all commits
Commits
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,164 @@ | ||
package handler | ||
|
||
import ( | ||
"encoding/json" | ||
"io/ioutil" | ||
"net/http" | ||
"net/url" | ||
"strings" | ||
|
||
"github.com/playlyfe/go-graphql" | ||
|
||
"golang.org/x/net/context" | ||
) | ||
|
||
//Shortcuts for the Content-Type header | ||
const ( | ||
ContentTypeJSON = "application/json" | ||
ContentTypeGraphQL = "application/graphql" | ||
ContentTypeFormURLEncoded = "application/x-www-form-urlencoded" | ||
) | ||
|
||
//Handler structure | ||
type Handler struct { | ||
Executor *graphql.Executor | ||
Context interface{} | ||
Pretty bool | ||
} | ||
|
||
//RequestParameters from query like " /graphql?query=getUser($id:ID){lastName}&variables={"id":"4"} " | ||
type RequestParameters struct { | ||
Query string `json:"query" url:"query" schema:"query"` | ||
Variables map[string]interface{} `json:"variables" url:"variables" schema:"variables"` | ||
OperationName string `json:"operationName" url:"operationName" schema:"operationName"` | ||
} | ||
|
||
//RequestParametersCompatibility represents an workaround for getting`variables` as a JSON string | ||
type RequestParametersCompatibility struct { | ||
Query string `json:"query" url:"query" schema:"query"` | ||
Variables string `json:"variables" url:"variables" schema:"variables"` | ||
OperationName string `json:"operationName" url:"operationName" schema:"operationName"` | ||
} | ||
|
||
func getFromURL(values url.Values) *RequestParameters { | ||
if values.Get("query") != "" { | ||
// get variables map | ||
var variables map[string]interface{} | ||
variablesStr := values.Get("variables") | ||
json.Unmarshal([]byte(variablesStr), variables) | ||
|
||
return &RequestParameters{ | ||
Query: values.Get("query"), | ||
Variables: variables, | ||
OperationName: values.Get("operationName"), | ||
} | ||
} | ||
|
||
return nil | ||
} | ||
|
||
// NewRequestParameters Parses a http.Request into GraphQL request options struct | ||
func NewRequestParameters(r *http.Request) *RequestParameters { | ||
if reqParams := getFromURL(r.URL.Query()); reqParams != nil { | ||
return reqParams | ||
} | ||
|
||
if r.Method != "POST" { | ||
return &RequestParameters{} | ||
} | ||
|
||
if r.Body == nil { | ||
return &RequestParameters{} | ||
} | ||
|
||
// TODO: improve Content-Type handling | ||
contentTypeStr := r.Header.Get("Content-Type") | ||
contentTypeTokens := strings.Split(contentTypeStr, ";") | ||
contentType := contentTypeTokens[0] | ||
|
||
switch contentType { | ||
case ContentTypeGraphQL: | ||
body, err := ioutil.ReadAll(r.Body) | ||
if err != nil { | ||
return &RequestParameters{} | ||
} | ||
return &RequestParameters{ | ||
Query: string(body), | ||
} | ||
case ContentTypeFormURLEncoded: | ||
if err := r.ParseForm(); err != nil { | ||
return &RequestParameters{} | ||
} | ||
|
||
if reqParams := getFromURL(r.PostForm); reqParams != nil { | ||
return reqParams | ||
} | ||
|
||
return &RequestParameters{} | ||
|
||
case ContentTypeJSON: | ||
fallthrough | ||
default: | ||
var params RequestParameters | ||
body, err := ioutil.ReadAll(r.Body) | ||
if err != nil { | ||
return ¶ms | ||
} | ||
err = json.Unmarshal(body, ¶ms) | ||
if err != nil { | ||
// Probably `variables` was sent as a string instead of an object. | ||
// So, we try to be polite and try to parse that as a JSON string | ||
var CompatibleParams RequestParametersCompatibility | ||
json.Unmarshal(body, &CompatibleParams) | ||
json.Unmarshal([]byte(CompatibleParams.Variables), ¶ms.Variables) | ||
} | ||
return ¶ms | ||
} | ||
} | ||
|
||
// ContextHandler provides an entrypoint into executing graphQL queries with a | ||
// user-provided context. | ||
func (h *Handler) ContextHandler(ctx context.Context, w http.ResponseWriter, r *http.Request) { | ||
// get query | ||
params := NewRequestParameters(r) | ||
// execute graphql query | ||
result, _ := (h.Executor).Execute(h.Context, params.Query, params.Variables, params.OperationName) | ||
|
||
if h.Pretty { | ||
w.WriteHeader(200) //http.StatusOK = 200 | ||
buff, _ := json.MarshalIndent(result, "", " ") | ||
w.Write(buff) | ||
} else { | ||
w.WriteHeader(200) //http.StatusOK = 200 | ||
buff, _ := json.Marshal(result) | ||
w.Write(buff) | ||
} | ||
} | ||
|
||
// ServeHTTP provides an entrypoint into executing graphQL queries. | ||
func (h *Handler) ServeHTTP(w http.ResponseWriter, r *http.Request) { | ||
h.ContextHandler(context.Background(), w, r) | ||
} | ||
|
||
//Config for handler of the schema | ||
type Config Handler | ||
|
||
//New config | ||
func New(c *Config) *Handler { | ||
if c == nil { | ||
c = &Config{ | ||
Executor: nil, | ||
Context: "", | ||
Pretty: true, | ||
} | ||
} | ||
if c.Executor == nil { | ||
panic("Undefined GraphQL Executor") | ||
} | ||
|
||
return &Handler{ | ||
Executor: c.Executor, | ||
Context: c.Context, | ||
Pretty: c.Pretty, | ||
} | ||
} |
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
zap (and grpc go) have nice patterns for extensible parameterisation. Should use that pattern here so we can evolve the functionality of the handler.