/
main.go
114 lines (102 loc) · 2.68 KB
/
main.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
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) {
idQuery, isOK := p.Args["id"].(string)
if isOK {
return data[idQuery], nil
}
return nil, 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
}
err = json.Unmarshal(content, result)
if err != nil {
isOK = false
fmt.Print("Error:", err)
}
return
}