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

defining package and using gzip #82

Open
wants to merge 6 commits into
base: master
Choose a base branch
from
Open
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
15 changes: 15 additions & 0 deletions go.mod
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
module github.com/joaopandolfi/graphql

go 1.20

require (
github.com/matryer/is v1.4.1
github.com/pkg/errors v0.9.1
github.com/stretchr/testify v1.8.4
)

require (
github.com/davecgh/go-spew v1.1.1 // indirect
github.com/pmezard/go-difflib v1.0.0 // indirect
gopkg.in/yaml.v3 v3.0.1 // indirect
)
14 changes: 14 additions & 0 deletions go.sum
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c=
github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
github.com/matryer/is v1.4.1 h1:55ehd8zaGABKLXQUe2awZ99BD/PTc2ls+KV/dXphgEQ=
github.com/matryer/is v1.4.1/go.mod h1:8I/i5uYgLzgsgEloJE1U6xx5HkBQpAZvepWuujKwMRU=
github.com/pkg/errors v0.9.1 h1:FEBLx1zS214owpjy7qsBeixbURkuhQAwrK5UwLGTwt4=
github.com/pkg/errors v0.9.1/go.mod h1:bwawxfHBFNV+L2hUp1rHADufV3IMtnDRdf1r5NINEl0=
github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM=
github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=
github.com/stretchr/testify v1.8.4 h1:CcVxjf3Q8PM0mHUKJCdn+eZZtm5yQwehR5yeSVQQcUk=
github.com/stretchr/testify v1.8.4/go.mod h1:sz/lmYIOXD/1dqDmKjjqLyZ2RngseejIcXlSw2iwfAo=
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405 h1:yhCVgyC4o1eVCa2tZl7eS0r+SDo693bJlVdllGtEeKM=
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA=
gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
109 changes: 83 additions & 26 deletions graphql.go
Original file line number Diff line number Diff line change
@@ -1,37 +1,39 @@
// Package graphql provides a low level GraphQL client.
//
// // create a client (safe to share across requests)
// client := graphql.NewClient("https://machinebox.io/graphql")
// // create a client (safe to share across requests)
// client := graphql.NewClient("https://machinebox.io/graphql")
//
// // make a request
// req := graphql.NewRequest(`
// query ($key: String!) {
// items (id:$key) {
// field1
// field2
// field3
// }
// }
// `)
// // make a request
// req := graphql.NewRequest(`
// query ($key: String!) {
// items (id:$key) {
// field1
// field2
// field3
// }
// }
// `)
//
// // set any variables
// req.Var("key", "value")
// // set any variables
// req.Var("key", "value")
//
// // run it and capture the response
// var respData ResponseStruct
// if err := client.Run(ctx, req, &respData); err != nil {
// log.Fatal(err)
// }
// // run it and capture the response
// var respData ResponseStruct
// if err := client.Run(ctx, req, &respData); err != nil {
// log.Fatal(err)
// }
//
// Specify client
// # Specify client
//
// To specify your own http.Client, use the WithHTTPClient option:
// httpclient := &http.Client{}
// client := graphql.NewClient("https://machinebox.io/graphql", graphql.WithHTTPClient(httpclient))
//
// httpclient := &http.Client{}
// client := graphql.NewClient("https://machinebox.io/graphql", graphql.WithHTTPClient(httpclient))
package graphql

import (
"bytes"
"compress/gzip"
"context"
"encoding/json"
"fmt"
Expand All @@ -47,6 +49,8 @@ type Client struct {
endpoint string
httpClient *http.Client
useMultipartForm bool
sendGzip bool
receiveGzip bool

// closeReq will close the request body immediately allowing for reuse of client
closeReq bool
Expand Down Expand Up @@ -113,13 +117,34 @@ func (c *Client) runWithJSON(ctx context.Context, req *Request, resp interface{}
gr := &graphResponse{
Data: resp,
}
if c.sendGzip {
var compressedData bytes.Buffer
gzipBuff := gzip.NewWriter(&compressedData)
if _, err := gzipBuff.Write(requestBody.Bytes()); err != nil {
return errors.Wrap(err, "gzipping body")
}
gzipBuff.Close()
requestBody = compressedData
}

r, err := http.NewRequest(http.MethodPost, c.endpoint, &requestBody)
if err != nil {
return err
}
r.Close = c.closeReq

r.Header.Set("Content-Type", "application/json; charset=utf-8")
r.Header.Set("Accept", "application/json; charset=utf-8")

if c.sendGzip {
r.Header.Set("Content-Encoding", "gzip")
}

if c.receiveGzip {
r.Header.Set("Accept-Encoding", "deflate, gzip")
r.Header.Set("Accept", "*/*")
}

for key, values := range req.Header {
for _, value := range values {
r.Header.Add(key, value)
Expand All @@ -131,11 +156,28 @@ func (c *Client) runWithJSON(ctx context.Context, req *Request, resp interface{}
if err != nil {
return err
}

defer res.Body.Close()
var buf bytes.Buffer
if _, err := io.Copy(&buf, res.Body); err != nil {
return errors.Wrap(err, "reading body")

if res.Header.Get("Content-Encoding") != "gzip" {
if _, err := io.Copy(&buf, res.Body); err != nil {
return errors.Wrap(err, "reading body")
}
} else {
r, err := gzip.NewReader(res.Body)
if err != nil {
return errors.Wrap(err, "reading gzip body")
}
var resB bytes.Buffer
_, err = resB.ReadFrom(r)
if err != nil {
return errors.Wrap(err, "reading gzip bytes")
}
r.Close()
buf = resB
}

c.logf("<< %s", buf.String())
if err := json.NewDecoder(&buf).Decode(&gr); err != nil {
if res.StatusCode != http.StatusOK {
Expand Down Expand Up @@ -223,7 +265,8 @@ func (c *Client) runWithPostFields(ctx context.Context, req *Request, resp inter

// WithHTTPClient specifies the underlying http.Client to use when
// making requests.
// NewClient(endpoint, WithHTTPClient(specificHTTPClient))
//
// NewClient(endpoint, WithHTTPClient(specificHTTPClient))
func WithHTTPClient(httpclient *http.Client) ClientOption {
return func(client *Client) {
client.httpClient = httpclient
Expand All @@ -238,7 +281,21 @@ func UseMultipartForm() ClientOption {
}
}

//ImmediatelyCloseReqBody will close the req body immediately after each request body is ready
// ReceiveGzip to perform requiests parsing payload response in gzip and reduce the payload
func ReceiveGzip() ClientOption {
return func(client *Client) {
client.receiveGzip = true
}
}

// SendGzip to perform requiests sending body in gzip and reduce the payload
func SendGzip() ClientOption {
return func(client *Client) {
client.sendGzip = true
}
}

// ImmediatelyCloseReqBody will close the req body immediately after each request body is ready
func ImmediatelyCloseReqBody() ClientOption {
return func(client *Client) {
client.closeReq = true
Expand Down
53 changes: 53 additions & 0 deletions graphql_gzip_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,53 @@
package graphql

import (
"bytes"
"compress/gzip"
"context"
"io"
"net/http"
"net/http/httptest"
"testing"
"time"

"github.com/stretchr/testify/assert"
)

func TestDoJSONGzipServerError(t *testing.T) {

var calls int
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
assert.Equal(t, r.Header.Get("Content-Encoding"), "gzip")

calls++
assert.Equal(t, r.Method, http.MethodPost)

body, err := io.ReadAll(r.Body)
assert.Nil(t, err)

compressedData := bytes.NewReader(body)

reader, err := gzip.NewReader(compressedData)
assert.Nil(t, err)

decodedData, err := io.ReadAll(reader)
assert.Nil(t, err)

b := decodedData

assert.Equal(t, string(b), `{"query":"query {}","variables":null}`+"\n")
w.WriteHeader(http.StatusInternalServerError)
io.WriteString(w, `Internal Server Error`)
}))
defer srv.Close()

ctx := context.Background()
client := NewClient(srv.URL, SendGzip(), ReceiveGzip())

ctx, cancel := context.WithTimeout(ctx, 1*time.Second)
defer cancel()
var responseData map[string]interface{}
err := client.Run(ctx, &Request{q: "query {}"}, &responseData)
assert.Equal(t, calls, 1) // calls
assert.Equal(t, err.Error(), "graphql: server returned a non-200 status code: 500")
}