From 82e40858c0b0d366c30528e575a243f45b9e1959 Mon Sep 17 00:00:00 2001 From: James Abbottsmith Date: Wed, 11 Sep 2019 15:28:49 +1000 Subject: [PATCH 1/2] Add support for additional headers in client --- client/client.go | 8 +++++++- client/client_test.go | 30 ++++++++++++++++++++++++++++++ 2 files changed, 37 insertions(+), 1 deletion(-) diff --git a/client/client.go b/client/client.go index fefe7948d3..721fcfd4e0 100644 --- a/client/client.go +++ b/client/client.go @@ -15,6 +15,7 @@ import ( type Client struct { url string client *http.Client + Header http.Header } // New creates a graphql client @@ -23,6 +24,9 @@ func New(url string, client ...*http.Client) *Client { url: url, } + p.Header = http.Header{} + p.Header.Add("Content-Type", "application/json") + if len(client) > 0 { p.client = client[0] } else { @@ -101,7 +105,9 @@ func (p *Client) RawPost(query string, options ...Option) (*ResponseData, error) return nil, fmt.Errorf("encode: %s", err.Error()) } - rawResponse, err := p.client.Post(p.url, "application/json", bytes.NewBuffer(requestBody)) + req, err := http.NewRequest("POST", p.url, bytes.NewBuffer(requestBody)) + req.Header = p.Header + rawResponse, err := p.client.Do(req) if err != nil { return nil, fmt.Errorf("post: %s", err.Error()) } diff --git a/client/client_test.go b/client/client_test.go index af58feb140..8de568831a 100644 --- a/client/client_test.go +++ b/client/client_test.go @@ -39,3 +39,33 @@ func TestClient(t *testing.T) { require.Equal(t, "bob", resp.Name) } + +func TestClientWithHeader(t *testing.T) { + h := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + b, err := ioutil.ReadAll(r.Body) + if err != nil { + panic(err) + } + require.Equal(t, `{"query":"user(id:$id){name}","variables":{"id":1}}`, string(b)) + + err = json.NewEncoder(w).Encode(map[string]interface{}{ + "data": map[string]interface{}{ + "name": "bob", + }, + }) + if err != nil { + panic(err) + } + })) + + c := client.New(h.URL) + c.Header.Add("Authorization", "mytoken") + + var resp struct { + Name string + } + + c.MustPost("user(id:$id){name}", &resp, client.Var("id", 1)) + + require.Equal(t, "bob", resp.Name) +} From aa6e367470909ab4d48973d8a8eafb30298a4b03 Mon Sep 17 00:00:00 2001 From: James Abbottsmith Date: Wed, 11 Sep 2019 15:36:51 +1000 Subject: [PATCH 2/2] missed an error check --- client/client.go | 3 +++ 1 file changed, 3 insertions(+) diff --git a/client/client.go b/client/client.go index 721fcfd4e0..423b5bf3d2 100644 --- a/client/client.go +++ b/client/client.go @@ -106,6 +106,9 @@ func (p *Client) RawPost(query string, options ...Option) (*ResponseData, error) } req, err := http.NewRequest("POST", p.url, bytes.NewBuffer(requestBody)) + if err != nil { + return nil, fmt.Errorf("creating request: %s", err.Error()) + } req.Header = p.Header rawResponse, err := p.client.Do(req) if err != nil {