Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Hotfix/857 #859

Closed
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
11 changes: 10 additions & 1 deletion client/client.go
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@ import (
type Client struct {
url string
client *http.Client
Header http.Header
}

// New creates a graphql client
Expand All @@ -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 {
Expand Down Expand Up @@ -101,7 +105,12 @@ 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))
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 {
return nil, fmt.Errorf("post: %s", err.Error())
}
Expand Down
30 changes: 30 additions & 0 deletions client/client_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -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)
}