wire auth to example, fix wire format, it's aliiiiiive!

This commit is contained in:
Ben Kraft
2019-12-25 21:33:12 -05:00
parent 4d880a701e
commit 7f6ab70ee3
2 changed files with 55 additions and 11 deletions
+39 -8
View File
@@ -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=<github token>")
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)
}
+16 -3
View File
@@ -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
}