package handler import ( "encoding/json" "html/template" "net/http" "github.com/graphql-go/graphql" ) // page is the page data structure of the rendered GraphiQL page type graphiqlPage struct { GraphiqlVersion string QueryString string ResultString string VariablesString string OperationName string } // renderGraphiQL renders the GraphiQL GUI func renderGraphiQL(w http.ResponseWriter, params graphql.Params) { t := template.New("GraphiQL") t, err := t.Parse(graphiqlTemplate) if err != nil { http.Error(w, err.Error(), http.StatusInternalServerError) return } // Create variables string vars, err := json.MarshalIndent(params.VariableValues, "", " ") if err != nil { http.Error(w, err.Error(), http.StatusInternalServerError) return } varsString := string(vars) if varsString == "null" { varsString = "" } // Create result string var resString string if params.RequestString == "" { resString = "" } else { result, err := json.MarshalIndent(graphql.Do(params), "", " ") if err != nil { http.Error(w, err.Error(), http.StatusInternalServerError) return } resString = string(result) } p := graphiqlPage{ GraphiqlVersion: graphiqlVersion, QueryString: params.RequestString, ResultString: resString, VariablesString: varsString, OperationName: params.OperationName, } err = t.ExecuteTemplate(w, "index", p) if err != nil { http.Error(w, err.Error(), http.StatusInternalServerError) } return } // graphiqlVersion is the current version of GraphiQL const graphiqlVersion = "0.11.3" // tmpl is the page template to render GraphiQL const graphiqlTemplate = ` {{ define "index" }} GraphiQL {{ end }} `