forked from friendsofgo/graphiql
/
server.go
35 lines (27 loc) · 817 Bytes
/
server.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
package graphiql
import (
"bytes"
"html/template"
"net/http"
)
// Handler define the struct of graphiql server
type Handler struct {
template *template.Template
Endpoint string
}
// NewGraphiqlHandler preparing the graphiql client to execute on your own server
// The endpoint is the url where you have your graphql api hosted
func NewGraphiqlHandler(endpoint string) (*Handler, error) {
t, err := preparingTemplate()
if err != nil {
return nil, err
}
return &Handler{Endpoint: endpoint, template: t}, nil
}
// ServeHTTP is a handler function for resolve graphiql client on servers
func (h *Handler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
graphiql := new(bytes.Buffer)
h.template.Execute(w, data(h.Endpoint))
w.Header().Set("Content-Type", "text/html")
w.Write(graphiql.Bytes())
}