Skip to content

Commit

Permalink
fix: Override headers passed to GQL service (#103)
Browse files Browse the repository at this point in the history
* fix: Override headers passed to GQL service

* test message

* always override

* tests

* fix tests
  • Loading branch information
romain-tadiello authored Feb 23, 2023
1 parent 77e6539 commit 39f5bc7
Show file tree
Hide file tree
Showing 2 changed files with 37 additions and 1 deletion.
7 changes: 6 additions & 1 deletion do.go
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,8 @@ const (
opMutation
)

const applicationJSON = "application/json"

// Operation is an encapsulation of all of the elements that are used to compose an operation
// using struct tags. The OperationType field should always be passed by reference in order for
// the data to be able to be marshaled back into it.
Expand Down Expand Up @@ -166,12 +168,15 @@ func (c *Client) do(ctx context.Context, body io.Reader, headers http.Header) (j
req.Header = headers

// The Content-Type of this request will always be application/json as per the GraphQL specification.
req.Header.Set("Content-Type", "application/json")
req.Header.Set("Content-Type", applicationJSON)

// We don't want this header to be set because then we won't get the luxury of the transport automatically
// decoding the response body for us, if it is encoded.
req.Header.Del("Accept-Encoding")

// Ensure headers compliance with GQL service expectations
headers.Set("Accept", applicationJSON)

// Do the GraphQL request using the HTTP client that was configured for this GraphQL client.
resp, err := c.httpClient.Do(req)
if err != nil {
Expand Down
31 changes: 31 additions & 0 deletions do_test.go
Original file line number Diff line number Diff line change
@@ -1,7 +1,9 @@
package goql

import (
"bytes"
"context"
"encoding/json"
"net/http"
"testing"

Expand Down Expand Up @@ -221,3 +223,32 @@ func TestDoStruct(t *testing.T) {
t.Run(test.Name, fn)
}
}

func TestDoHeadersOverride(t *testing.T) {
ts := graphql_test.NewServer(t, true)
t.Cleanup(ts.Close)
var buf bytes.Buffer
query := "query"
if err := json.NewEncoder(&buf).Encode(request{ //nolint:gocritic
Query: query,
Variables: nil,
}); err != nil {
t.Fatalf("error building buffer: %v", err)
}
headers := http.Header{}
client := NewClient(ts.URL, DefaultClientOptions)
client.do(context.Background(), &buf, headers)
if headers.Get("Accept") != applicationJSON {
t.Fatal("Unexpected header Accept")
}
headers.Set("Accept", "some header")
client.do(context.Background(), &buf, headers)
if headers.Get("Accept") != applicationJSON {
t.Fatal("Unexpected header Accept value")
}
headers.Set("Accept", applicationJSON)
client.do(context.Background(), &buf, headers)
if headers.Get("Accept") != applicationJSON {
t.Fatal("Unexpected header Accept value")
}
}

0 comments on commit 39f5bc7

Please sign in to comment.