// _ _ // __ _____ __ ___ ___ __ _| |_ ___ // \ \ /\ / / _ \/ _` \ \ / / |/ _` | __/ _ \ // \ V V / __/ (_| |\ V /| | (_| | || __/ // \_/\_/ \___|\__,_| \_/ |_|\__,_|\__\___| // // Copyright © 2016 - 2024 Weaviate B.V. All rights reserved. // // CONTACT: hello@weaviate.io // // Based on `graphiql.go` from https://github.com/graphql-go/handler // only made RenderGraphiQL a public function. package graphiql import ( "encoding/json" "html/template" "net/http" "strings" ) // graphiqlVersion is the current version of GraphiQL const graphiqlVersion = "0.11.11" // graphiqlData is the page data structure of the rendered GraphiQL page type graphiqlData struct { GraphiqlVersion string QueryString string Variables string OperationName string AuthKey string AuthToken string } func AddMiddleware(next http.Handler) http.Handler { return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { if strings.HasPrefix(r.URL.Path, "/v1/graphql") && r.Method == http.MethodGet { renderGraphiQL(w, r) } else { next.ServeHTTP(w, r) } }) } // renderGraphiQL renders the GraphiQL GUI func renderGraphiQL(w http.ResponseWriter, r *http.Request) { w.Header().Set("WWW-Authenticate", `Basic realm="Provide your key and token (as username as password respectively)"`) user, password, authOk := r.BasicAuth() if !authOk { http.Error(w, "Not authorized", 401) return } queryParams := r.URL.Query() t := template.New("GraphiQL") t, err := t.Parse(graphiqlTemplate) if err != nil { http.Error(w, err.Error(), http.StatusInternalServerError) return } // Attempt to deserialize the 'variables' query key to something reasonable. var queryVars interface{} err = json.Unmarshal([]byte(queryParams.Get("variables")), &queryVars) var varsString string if err == nil { vars, err := json.MarshalIndent(queryVars, "", " ") if err != nil { http.Error(w, err.Error(), http.StatusInternalServerError) return } varsString = string(vars) if varsString == "null" { varsString = "" } } // Create result string d := graphiqlData{ GraphiqlVersion: graphiqlVersion, QueryString: queryParams.Get("query"), Variables: varsString, OperationName: queryParams.Get("operationName"), AuthKey: user, AuthToken: password, } err = t.ExecuteTemplate(w, "index", d) if err != nil { http.Error(w, err.Error(), http.StatusInternalServerError) } } // tmpl is the page template to render GraphiQL const graphiqlTemplate = ` {{ define "index" }} GraphiQL
Loading...
{{ end }} `