Skip to content

Instantly share code, notes, and snippets.



Last active Jan 21, 2017
What would you like to do?
Example of creating custom `graphql-go/handler` using `handler.NewRequestOptions()` to parse http.Requests
package main
import (
func myCustomGraphQLHandler(schema *graphql.Schema) func(http.ResponseWriter, *http.Request) {
if schema == nil {
// panic at time of initial execution
panic("Graphql schema cannot be nil")
return func(rw http.ResponseWriter, r *http.Request) {
// parse http.Request into handler.RequestOptions
opts := handler.NewRequestOptions(r)
// inject context objects http.ResponseWrite and *http.Request into rootValue
// there is an alternative example of using `net/context` to store context instead of using rootValue
rootValue := map[string]interface{}{
"response": rw,
"request": r,
"viewer": "john_doe",
// execute graphql query
// here, we passed in Query, Variables and OperationName extracted from http.Request
params := graphql.Params{
Schema: *schema,
RequestString: opts.Query,
VariableValues: opts.Variables,
OperationName: opts.OperationName,
RootObject: rootValue,
result := graphql.Do(params)
// one way to render JSON without use of external libraries
// alternatively, you can use libraries like `unrolled/render`
js, err := json.Marshal(result)
if err != nil {
http.Error(rw, err.Error(), http.StatusInternalServerError)
rw.Header().Set("Content-Type", "application/json")
func main() {
http.HandleFunc("/graphql/", myCustomGraphQLHandler(&starwars.Schema))
http.ListenAndServe(":3000", nil)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.