/
main.go
74 lines (66 loc) · 1.53 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
package main
import (
"context"
"encoding/json"
"fmt"
"log"
"net/http"
"github.com/graphql-go/graphql"
)
var Schema graphql.Schema
var userType = graphql.NewObject(
graphql.ObjectConfig{
Name: "User",
Fields: graphql.Fields{
"id": &graphql.Field{
Type: graphql.String,
},
"name": &graphql.Field{
Type: graphql.String,
},
},
},
)
var queryType = graphql.NewObject(
graphql.ObjectConfig{
Name: "Query",
Fields: graphql.Fields{
"me": &graphql.Field{
Type: userType,
Resolve: func(p graphql.ResolveParams) (interface{}, error) {
return p.Context.Value("currentUser"), nil
},
},
},
})
func graphqlHandler(w http.ResponseWriter, r *http.Request) {
user := struct {
ID int `json:"id"`
Name string `json:"name"`
}{1, "cool user"}
result := graphql.Do(graphql.Params{
Schema: Schema,
RequestString: r.URL.Query().Get("query"),
Context: context.WithValue(context.Background(), "currentUser", user),
})
if len(result.Errors) > 0 {
log.Printf("wrong result, unexpected errors: %v", result.Errors)
return
}
json.NewEncoder(w).Encode(result)
}
func main() {
http.HandleFunc("/graphql", graphqlHandler)
fmt.Println("Now server is running on port 8080")
fmt.Println("Test with Get : curl -g 'http://localhost:8080/graphql?query={me{id,name}}'")
http.ListenAndServe(":8080", nil)
}
func init() {
s, err := graphql.NewSchema(graphql.SchemaConfig{
Query: queryType,
})
if err != nil {
log.Fatalf("failed to create schema, error: %v", err)
}
Schema = s
}