-
Notifications
You must be signed in to change notification settings - Fork 118
/
http.go
42 lines (34 loc) · 1.14 KB
/
http.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
// Package http handles GraphQL HTTP Requests including WebSocket Upgrades.
package http
import (
"bytes"
"net/http"
log "github.com/jensneuse/abstractlogger"
"github.com/jensneuse/graphql-go-tools/pkg/graphql"
)
const (
httpHeaderContentType string = "Content-Type"
httpContentTypeApplicationJson string = "application/json"
)
func (g *GraphQLHTTPRequestHandler) handleHTTP(w http.ResponseWriter, r *http.Request) {
var err error
var gqlRequest graphql.Request
if err = graphql.UnmarshalHttpRequest(r, &gqlRequest); err != nil {
g.log.Error("UnmarshalHttpRequest", log.Error(err))
w.WriteHeader(http.StatusBadRequest)
return
}
buf := bytes.NewBuffer(make([]byte, 0, 4096))
resultWriter := graphql.NewEngineResultWriterFromBuffer(buf)
if err = g.engine.Execute(r.Context(), &gqlRequest, &resultWriter); err != nil {
g.log.Error("engine.Execute", log.Error(err))
w.WriteHeader(http.StatusInternalServerError)
return
}
w.Header().Add(httpHeaderContentType, httpContentTypeApplicationJson)
w.WriteHeader(http.StatusOK)
if _, err = w.Write(buf.Bytes()); err != nil {
g.log.Error("write response", log.Error(err))
return
}
}