Skip to content

Instantly share code, notes, and snippets.

@larryaasen
Last active February 25, 2018 15:45
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save larryaasen/41a6fca9116489ec461646ea161cef6f to your computer and use it in GitHub Desktop.
Save larryaasen/41a6fca9116489ec461646ea161cef6f to your computer and use it in GitHub Desktop.
GraphQL sample using graphql-go/graphql and Go (Golang)
/*
Install:
$ go get github.com/graphql-go
$ go run server2.go
Examples:
http://localhost:8080/graphql?query={users{name}}
http://localhost:8080/graphql?query={user(id:"1"){name}}
*/
package main
import (
"encoding/json"
"fmt"
// "io/ioutil"
"net/http"
"github.com/graphql-go/graphql"
)
type user struct {
ID string `json:"id"`
Name string `json:"name"`
}
var data map[string]user
/*
Create User object type with fields "id" and "name" by using GraphQLObjectTypeConfig:
- Name: name of object type
- Fields: a map of fields by using GraphQLFields
Setup type of field use GraphQLFieldConfig
*/
var userType = graphql.NewObject(
graphql.ObjectConfig{
Name: "User",
Fields: graphql.Fields{
"id": &graphql.Field{
Type: graphql.String,
},
"name": &graphql.Field{
Type: graphql.String,
},
},
},
)
/*
Create Query object type with fields "user" has type [userType] by using GraphQLObjectTypeConfig:
- Name: name of object type
- Fields: a map of fields by using GraphQLFields
Setup type of field use GraphQLFieldConfig to define:
- Type: type of field
- Args: arguments to query with current field
- Resolve: function to query data using params from [Args] and return value with current type
*/
var queryType = graphql.NewObject(
graphql.ObjectConfig{
Name: "Query",
Fields: graphql.Fields{
"user": &graphql.Field{
Type: userType,
Args: graphql.FieldConfigArgument{
"id": &graphql.ArgumentConfig{
Type: graphql.String,
},
},
Resolve: func(p graphql.ResolveParams) (interface{}, error) {
fmt.Printf("user resolver start\n")
idQuery, isOK := p.Args["id"].(string)
fmt.Printf("user resolver idQuery %v, isOK %v\n", idQuery, isOK)
if isOK {
return data[idQuery], nil
}
return nil, nil
},
},
"users": &graphql.Field{
Type: graphql.NewList(userType),
Resolve: func(p graphql.ResolveParams) (interface{}, error) {
fmt.Printf("users resolver start\n")
users := make([]user, 0)
users = append(users, data["1"])
users = append(users, data["2"])
users = append(users, data["3"])
return users, nil
},
},
},
})
var schema, _ = graphql.NewSchema(
graphql.SchemaConfig{
Query: queryType,
},
)
func executeQuery(query string, schema graphql.Schema) *graphql.Result {
result := graphql.Do(graphql.Params{
Schema: schema,
RequestString: query,
})
if len(result.Errors) > 0 {
fmt.Printf("wrong result, unexpected errors: %v", result.Errors)
}
return result
}
func main() {
_ = importJSONDataFromFile("data.json", &data)
http.HandleFunc("/graphql", func(w http.ResponseWriter, r *http.Request) {
result := executeQuery(r.URL.Query().Get("query"), schema)
json.NewEncoder(w).Encode(result)
})
fmt.Println("Now server is running on port 8080")
fmt.Println("Test with Get : curl -g 'http://localhost:8080/graphql?query={user(id:\"1\"){name}}'")
http.ListenAndServe(":8080", nil)
}
//Helper function to import json from file to map
func importJSONDataFromFile(fileName string, result interface{}) (isOK bool) {
isOK = true
// content, err := ioutil.ReadFile(fileName)
// if err != nil {
// fmt.Print("Error:", err)
// isOK = false
// }
content := DataContents
err := json.Unmarshal([]byte(content), result)
if err != nil {
isOK = false
fmt.Print("Error:", err)
}
return
}
var DataContents = `
{
"1": {
"id": "1",
"name": "Dan"
},
"2": {
"id": "2",
"name": "Lee"
},
"3": {
"id": "3",
"name": "Nick"
}
}
`
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment