-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathhandler_graphql.go
43 lines (33 loc) · 1.1 KB
/
handler_graphql.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
package main
import (
"encoding/json"
"github.com/graph-gophers/graphql-go"
"net/http"
)
type GraphQLHandler struct {
schema *graphql.Schema
}
func NewGraphQLHandler(schema *graphql.Schema) *GraphQLHandler {
return &GraphQLHandler{schema: schema}
}
func (h *GraphQLHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
var params struct {
Query string `json:"query"`
OperationName string `json:"operationName"`
Variables map[string]interface{} `json:"variables"`
}
if err := json.NewDecoder(r.Body).Decode(¶ms); err != nil {
http.Error(w, err.Error(), http.StatusBadRequest)
return
}
// by mn ctx := h.Loaders.Attach(r.Context())
ctx := r.Context()
response := h.schema.Exec(ctx, params.Query, params.OperationName, params.Variables)
responseJSON, err := json.Marshal(response)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
w.Header().Set("Content-Type", "application/json")
w.Write(responseJSON)
}