forked from OscarYuen/go-graphql-starter
/
graphql.go
36 lines (31 loc) · 965 Bytes
/
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
package handler
import (
"encoding/json"
"github.com/OscarYuen/go-graphql-starter/loader"
"github.com/graph-gophers/graphql-go"
"net/http"
)
type GraphQL struct {
Schema *graphql.Schema
Loaders loader.LoaderCollection
}
func (h *GraphQL) 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
}
ctx := h.Loaders.Attach(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)
}