Debian Codegraph @

example/graphqldev/main.go

raw symbols SCIP
1 // graphqldev is a test program currently being used for developing graphql package.
2 // It performs queries against a local test GraphQL server instance.
3 //
4 // It's not meant to be a clean or readable example. But it's functional.
5 // Better, actual examples will be created in the future.
6 package main
7
8 import (
9 "context"
10 "encoding/json"
11 "flag"
12 "log"
13 "net/http"
14 "net/http/httptest"
15 "os"
16
17 graphqlserver "github.com/graph-gophers/graphql-go"
18 "github.com/graph-gophers/graphql-go/example/starwars"
19 "github.com/graph-gophers/graphql-go/relay"
20 "github.com/shurcooL/graphql"
21 )
22
23 func main() {
24 flag.Parse()
25
26 err := run()
27 if err != nil {
28 log.Println(err)
29 }
30 }
31
32 func run() error {
33 // Set up a GraphQL server.
34 schema, err := graphqlserver.ParseSchema(starwars.Schema, &starwars.Resolver{})
35 if err != nil {
36 return err
37 }
38 mux := http.NewServeMux()
39 mux.Handle("/query", &relay.Handler{Schema: schema})
40
41 client := graphql.NewClient("/query", &http.Client{Transport: localRoundTripper{handler: mux}})
42
43 /*
44 query {
45 hero {
46 id
47 name
48 }
49 character(id: "1003") {
50 name
51 friends {
52 name
53 __typename
54 }
55 appearsIn
56 }
57 }
58 */
59 var q struct {
60 Hero struct {
61 ID graphql.ID
62 Name graphql.String
63 }
64 Character struct {
65 Name graphql.String
66 Friends []struct {
67 Name graphql.String
68 Typename graphql.String `graphql:"__typename"`
69 }
70 AppearsIn []graphql.String
71 } `graphql:"character(id: $characterID)"`
72 }
73 variables := map[string]interface{}{
74 "characterID": graphql.ID("1003"),
75 }
76 err = client.Query(context.Background(), &q, variables)
77 if err != nil {
78 return err
79 }
80 print(q)
81
82 return nil
83 }
84
85 // print pretty prints v to stdout. It panics on any error.
86 func print(v interface{}) {
87 w := json.NewEncoder(os.Stdout)
88 w.SetIndent("", "\t")
89 err := w.Encode(v)
90 if err != nil {
91 panic(err)
92 }
93 }
94
95 // localRoundTripper is an http.RoundTripper that executes HTTP transactions
96 // by using handler directly, instead of going over an HTTP connection.
97 type localRoundTripper struct {
98 handler http.Handler
99 }
100
101 func (l localRoundTripper) RoundTrip(req *http.Request) (*http.Response, error) {
102 w := httptest.NewRecorder()
103 l.handler.ServeHTTP(w, req)
104 return w.Result(), nil
105 }