forked from cli/shurcooL-graphql
-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
105 lines (94 loc) · 2.19 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
// graphqldev is a test program currently being used for developing graphql package.
// It performs queries against a local test GraphQL server instance.
//
// It's not meant to be a clean or readable example. But it's functional.
// Better, actual examples will be created in the future.
package main
import (
"context"
"encoding/json"
"flag"
"log"
"net/http"
"net/http/httptest"
"os"
graphqlserver "github.com/graph-gophers/graphql-go"
"github.com/graph-gophers/graphql-go/example/starwars"
"github.com/graph-gophers/graphql-go/relay"
"github.com/shurcooL/graphql"
)
func main() {
flag.Parse()
err := run()
if err != nil {
log.Println(err)
}
}
func run() error {
// Set up a GraphQL server.
schema, err := graphqlserver.ParseSchema(starwars.Schema, &starwars.Resolver{})
if err != nil {
return err
}
mux := http.NewServeMux()
mux.Handle("/query", &relay.Handler{Schema: schema})
client := graphql.NewClient("/query", &http.Client{Transport: localRoundTripper{handler: mux}})
/*
query {
hero {
id
name
}
character(id: "1003") {
name
friends {
name
__typename
}
appearsIn
}
}
*/
var q struct {
Hero struct {
ID graphql.ID
Name graphql.String
}
Character struct {
Name graphql.String
Friends []struct {
Name graphql.String
Typename graphql.String `graphql:"__typename"`
}
AppearsIn []graphql.String
} `graphql:"character(id: $characterID)"`
}
variables := map[string]interface{}{
"characterID": graphql.ID("1003"),
}
err = client.Query(context.Background(), &q, variables)
if err != nil {
return err
}
print(q)
return nil
}
// print pretty prints v to stdout. It panics on any error.
func print(v interface{}) {
w := json.NewEncoder(os.Stdout)
w.SetIndent("", "\t")
err := w.Encode(v)
if err != nil {
panic(err)
}
}
// localRoundTripper is an http.RoundTripper that executes HTTP transactions
// by using handler directly, instead of going over an HTTP connection.
type localRoundTripper struct {
handler http.Handler
}
func (l localRoundTripper) RoundTrip(req *http.Request) (*http.Response, error) {
w := httptest.NewRecorder()
l.handler.ServeHTTP(w, req)
return w.Result(), nil
}