Last active
May 28, 2024 00:29
-
-
Save sogko/a622e1aa5a1e022c2228 to your computer and use it in GitHub Desktop.
Example of creating custom `graphql-go/handler` using `handler.NewRequestOptions()` to parse http.Requests
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main | |
import ( | |
"encoding/json" | |
"net/http" | |
"github.com/graphql-go/graphql" | |
"github.com/graphql-go/handler" | |
"github.com/graphql-go/relay/examples/starwars" | |
) | |
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) | |
return | |
} | |
rw.Header().Set("Content-Type", "application/json") | |
rw.Write(js) | |
} | |
} | |
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