diff --git a/do.go b/do.go index 0453d33..d94938c 100644 --- a/do.go +++ b/do.go @@ -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. @@ -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 { diff --git a/do_test.go b/do_test.go index aa9622d..efcd4cb 100644 --- a/do_test.go +++ b/do_test.go @@ -1,7 +1,9 @@ package goql import ( + "bytes" "context" + "encoding/json" "net/http" "testing" @@ -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") + } +}