From 7f6ab70ee3e846f911bc91aaf2770e775f5dbf95 Mon Sep 17 00:00:00 2001 From: Ben Kraft Date: Wed, 25 Dec 2019 21:33:12 -0500 Subject: [PATCH] wire auth to example, fix wire format, it's aliiiiiive! --- example/caller.go | 47 +++++++++++++++++++++++++++++++++++++++-------- graphql/client.go | 19 ++++++++++++++++--- 2 files changed, 55 insertions(+), 11 deletions(-) diff --git a/example/caller.go b/example/caller.go index a1e1d77..52bcd6e 100644 --- a/example/caller.go +++ b/example/caller.go @@ -3,17 +3,48 @@ package example import ( "context" "fmt" + "net/http" "os" "github.com/Khan/genql/graphql" ) -func Main() { - client := graphql.NewClient("https://api.github.com/graphql", nil) - resp, err := getViewer(context.Background(), client) - if err != nil { - fmt.Println(err) - os.Exit(1) - } - fmt.Println("you are:", resp.Viewer.Name) +type authedTransport struct { + key string + wrapped http.RoundTripper +} + +func (t *authedTransport) RoundTrip(req *http.Request) (*http.Response, error) { + req.Header.Set("Authorization", "bearer "+t.key) + return t.wrapped.RoundTrip(req) +} + +func Main() { + var err error + defer func() { + if err != nil { + fmt.Println(err) + os.Exit(1) + } + }() + + key := os.Getenv("KEY") + if key == "" { + err = fmt.Errorf("must set KEY=") + return + } + + httpClient := http.Client{ + Transport: &authedTransport{ + key: key, + wrapped: http.DefaultTransport, + }, + } + graphqlClient := graphql.NewClient("https://api.github.com/graphql", &httpClient) + resp, err := getViewer(context.Background(), graphqlClient) + if err != nil { + return + } + + fmt.Println("you are:", *resp.Viewer.Name) } diff --git a/graphql/client.go b/graphql/client.go index 2f043d2..0c493df 100644 --- a/graphql/client.go +++ b/graphql/client.go @@ -1,12 +1,12 @@ package graphql import ( + "bytes" "context" "encoding/json" "fmt" "io/ioutil" "net/http" - "strings" "github.com/vektah/gqlparser/gqlerror" ) @@ -24,11 +24,24 @@ func NewClient(endpoint string, httpClient *http.Client) *Client { return &Client{endpoint, http.MethodPost, httpClient} } +type payload struct { + Query string `json:"query"` + Variables map[string]string `json:"variables"` +} + func (client *Client) MakeRequest(ctx context.Context, query string, retval interface{}) error { + body, err := json.Marshal(payload{ + Query: query, + Variables: nil, // TODO + }) + if err != nil { + return err + } + req, err := http.NewRequest( client.method, client.endpoint, - strings.NewReader(query)) + bytes.NewReader(body)) if err != nil { return err } @@ -40,7 +53,7 @@ func (client *Client) MakeRequest(ctx context.Context, query string, retval inte } defer resp.Body.Close() - body, err := ioutil.ReadAll(resp.Body) + body, err = ioutil.ReadAll(resp.Body) if err != nil { return err }