server.go
719 字节
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
package server
import (
"encoding/json"
"net/http"
"github.com/bradford-hamilton/go-graphql-api/gql"
"github.com/go-chi/render"
"github.com/graphql-go/graphql"
)
type Server struct {
GqlSchema *graphql.Schema
}
type reqBody struct {
Query string `json:"query"`
}
func (s *Server) GraphQL() http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
if r.Body == nil {
http.Error(w, "Must provide graphql query in request body", 400)
return
}
var rBody reqBody
err := json.NewDecoder(r.Body).Decode(&rBody)
if err != nil {
http.Error(w, "Error parsing JSON request body", 400)
}
result := gql.ExecuteQuery(rBody.Query, *s.GqlSchema)
render.JSON(w, r, result)
}
}