diff --git a/gql/graphiql.go b/gql/graphiql.go new file mode 100644 index 00000000..59b08161 --- /dev/null +++ b/gql/graphiql.go @@ -0,0 +1,181 @@ +package gql + +import ( + "bytes" + "fmt" + "html/template" + "net/http" +) + +// GraphiQL is an in-browser IDE for exploring GraphiQL APIs. +// This handler returns GraphiQL when requested. +// +// For more information, see https://github.com/graphql/graphiql. + +func respond(w http.ResponseWriter, body []byte, code int) { + w.Header().Set("Content-Type", "application/json; charset=utf-8") + w.Header().Set("X-Content-Type-Options", "nosniff") + w.WriteHeader(code) + _, _ = w.Write(body) +} + +func errorJSON(msg string) []byte { + buf := bytes.Buffer{} + fmt.Fprintf(&buf, `{"error": "%s"}`, msg) + return buf.Bytes() +} + +func PlaygroundHandler(apiUrl string) http.HandlerFunc { + return func(w http.ResponseWriter, r *http.Request) { + if r.Method != "GET" { + respond(w, errorJSON("only GET requests are supported"), http.StatusMethodNotAllowed) + return + } + w.Header().Set("Content-Type", "text/html") + err := page.Execute(w, map[string]interface{}{ + "apiUrl": apiUrl, + }) + if err != nil { + panic(err) + } + } +} + +// https://github.com/graphql/graphiql/blob/main/examples/graphiql-cdn/index.html +var page = template.Must(template.New("graphiql").Parse(` + + +
+