-
Notifications
You must be signed in to change notification settings - Fork 0
/
handler.go
92 lines (85 loc) · 2.01 KB
/
handler.go
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
package handler
import (
"encoding/json"
"fmt"
"html"
"io/ioutil"
"net/http"
"github.com/rigglo/gql"
)
type Config struct {
Executor *gql.Executor
GraphiQL bool
Pretty bool
}
func New(c Config) http.Handler {
return &handler{
conf: c,
}
}
type handler struct {
conf Config
}
func (h *handler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
params := new(gql.Params)
switch r.Method {
case http.MethodGet:
{
params = &gql.Params{
Query: html.UnescapeString(r.URL.Query().Get("query")),
Variables: map[string]interface{}{}, // TODO: find a way of doing this..
OperationName: r.URL.Query().Get("operationName"),
}
if r.URL.Query().Get("variables") != "" {
varsRaw := html.UnescapeString(r.URL.Query().Get("variables"))
err := json.Unmarshal([]byte(varsRaw), ¶ms.Variables)
if err != nil {
http.Error(w, `{"error": "invalid variables format"}`, http.StatusBadRequest)
return
}
}
if h.conf.GraphiQL {
w.Header().Set("Content-Type", "text/html; charset=utf-8")
fmt.Fprint(w, graphiql)
return
}
}
case http.MethodPost:
{
if r.Header.Get("Content-Type") == "application/json" {
bs, err := ioutil.ReadAll(r.Body)
if err != nil {
break
}
err = json.Unmarshal(bs, params)
if err != nil {
http.Error(w, `{"error": "invalid parameters format"}`, http.StatusBadRequest)
return
}
}
}
}
if params != nil {
var (
bs []byte
err error
)
if h.conf.Pretty {
bs, err = json.MarshalIndent(h.conf.Executor.Execute(r.Context(), *params), "", "\t")
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
} else {
bs, err = json.Marshal(h.conf.Executor.Execute(r.Context(), *params))
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
}
w.Header().Set("Content-Type", "application/json")
fmt.Fprint(w, string(bs))
return
}
http.Error(w, "invalid query parameters", http.StatusBadRequest)
}