| 1 |
|
| 2 |
|
| 3 |
|
| 4 |
|
| 5 |
|
| 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 |
|
| 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 |
|
| 45 |
|
| 46 |
|
| 47 |
|
| 48 |
|
| 49 |
|
| 50 |
|
| 51 |
|
| 52 |
|
| 53 |
|
| 54 |
|
| 55 |
|
| 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 |
|
| 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 |
|
| 96 |
|
| 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 |
} |