1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
|
package handler
import (
"encoding/json"
"io/ioutil"
"net/http"
"net/url"
"strings"
"github.com/graphql-go/graphql"
"context"
)
const (
ContentTypeJSON = "application/json"
ContentTypeGraphQL = "application/graphql"
ContentTypeFormURLEncoded = "application/x-www-form-urlencoded"
)
type Handler struct {
Schema *graphql.Schema
pretty bool
graphiql bool
}
type RequestOptions 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"`
}
// a workaround for getting`variables` as a JSON string
type requestOptionsCompatibility 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 getFromForm(values url.Values) *RequestOptions {
query := values.Get("query")
if query != "" {
// get variables map
variables := make(map[string]interface{}, len(values))
variablesStr := values.Get("variables")
json.Unmarshal([]byte(variablesStr), &variables)
return &RequestOptions{
Query: query,
Variables: variables,
OperationName: values.Get("operationName"),
}
}
return nil
}
// RequestOptions Parses a http.Request into GraphQL request options struct
func NewRequestOptions(r *http.Request) *RequestOptions {
if reqOpt := getFromForm(r.URL.Query()); reqOpt != nil {
return reqOpt
}
if r.Method != "POST" {
return &RequestOptions{}
}
if r.Body == nil {
return &RequestOptions{}
}
// 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 &RequestOptions{}
}
return &RequestOptions{
Query: string(body),
}
case ContentTypeFormURLEncoded:
if err := r.ParseForm(); err != nil {
return &RequestOptions{}
}
if reqOpt := getFromForm(r.PostForm); reqOpt != nil {
return reqOpt
}
return &RequestOptions{}
case ContentTypeJSON:
fallthrough
default:
var opts RequestOptions
body, err := ioutil.ReadAll(r.Body)
if err != nil {
return &opts
}
err = json.Unmarshal(body, &opts)
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 optsCompatible requestOptionsCompatibility
json.Unmarshal(body, &optsCompatible)
json.Unmarshal([]byte(optsCompatible.Variables), &opts.Variables)
}
return &opts
}
}
// 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
opts := NewRequestOptions(r)
// execute graphql query
params := graphql.Params{
Schema: *h.Schema,
RequestString: opts.Query,
VariableValues: opts.Variables,
OperationName: opts.OperationName,
Context: ctx,
}
result := graphql.Do(params)
if h.graphiql {
acceptHeader := r.Header.Get("Accept")
_, raw := r.URL.Query()["raw"]
if !raw && !strings.Contains(acceptHeader, "application/json") && strings.Contains(acceptHeader, "text/html") {
renderGraphiQL(w, params)
return
}
}
// use proper JSON Header
w.Header().Add("Content-Type", "application/json; charset=utf-8")
if h.pretty {
w.WriteHeader(http.StatusOK)
buff, _ := json.MarshalIndent(result, "", "\t")
w.Write(buff)
} else {
w.WriteHeader(http.StatusOK)
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(r.Context(), w, r)
}
type Config struct {
Schema *graphql.Schema
Pretty bool
GraphiQL bool
}
func NewConfig() *Config {
return &Config{
Schema: nil,
Pretty: true,
GraphiQL: true,
}
}
func New(p *Config) *Handler {
if p == nil {
p = NewConfig()
}
if p.Schema == nil {
panic("undefined GraphQL schema")
}
return &Handler{
Schema: p.Schema,
pretty: p.Pretty,
graphiql: p.GraphiQL,
}
}
|