From 333ec58bd23261b4fa1f819306c22f1ca14226a1 Mon Sep 17 00:00:00 2001 From: Lukasz Raczylo Date: Sat, 2 Oct 2021 19:10:56 +0100 Subject: [PATCH] Add support for the query headers. --- README.md | 13 ++++--------- gql.go | 9 +++++---- gql_test.go | 7 +++---- pkg/logging/logging.go | 5 +++-- query.go | 17 +++++++++++++---- query_bench_test.go | 4 ++-- query_test.go | 6 +++--- 7 files changed, 33 insertions(+), 28 deletions(-) diff --git a/README.md b/README.md index d2677bd..39b8bca 100644 --- a/README.md +++ b/README.md @@ -8,7 +8,7 @@ Ps. It's Hasura friendly. - [Reasoning](#reasoning) - [Features](#features) - [Usage example](#usage-example) - - [Setting GraphQL endpoint](#setting-graphql-endpoint) + - [Environment variables](#environment-variables) - [Example reader code](#example-reader-code) - [Working with results](#working-with-results) @@ -27,15 +27,10 @@ Therefore, I present you the simple client to which you can copy & paste your gr ## Usage example -### Setting GraphQL endpoint +### Environment variables -You can set the endpoint variable within your code - -```go -gql.GraphQLUrl = "http://127.0.0.1:9090/v1/graphql" -``` - -or as an environment variable `GRAPHQL_ENDPOINT=http://127.0.0.1:9090/v1/graphql` +* `GRAPHQL_ENDPOINT` - Your GraphQL endpoint. Default: `http://127.0.0.1:9090/v1/graphql` +* `LOG_LEVEL` - Logging level. Default: `info` ### Example reader code diff --git a/gql.go b/gql.go index e70574a..4dea7c1 100644 --- a/gql.go +++ b/gql.go @@ -28,7 +28,7 @@ var ( json = jsoniter.ConfigCompatibleWithStandardLibrary ) -type connHandler struct { +type GraphQL struct { Endpoint string HttpClient *http.Client Log *logging.LogConfig @@ -45,12 +45,13 @@ func pickGraphqlEndpoint() (graphqlEndpoint string) { return graphqlEndpoint } -func NewConnection() *connHandler { - return &connHandler{ +func NewConnection() *GraphQL { + return &GraphQL{ Endpoint: pickGraphqlEndpoint(), HttpClient: &http.Client{ Transport: &http2.Transport{ - AllowHTTP: true, + DisableCompression: true, + AllowHTTP: true, DialTLS: func(network, addr string, cfg *tls.Config) (net.Conn, error) { return net.Dial(network, addr) }, diff --git a/gql_test.go b/gql_test.go index e9be547..a75e87c 100644 --- a/gql_test.go +++ b/gql_test.go @@ -33,26 +33,25 @@ func TestSuiteRun(t *testing.T) { func (suite *TestSuite) TestNewConnection() { type args struct { endpoint string - debug bool } tests := []struct { name string args args - want *connHandler + want *GraphQL }{ { name: "New connection: Env variable endpoint", args: args{ endpoint: "http://localhost:8080/graphql", }, - want: &connHandler{ + want: &GraphQL{ Endpoint: "http://localhost:8080/graphql", }, }, { name: "New connection: No env variable endpoint", args: args{}, - want: &connHandler{ + want: &GraphQL{ Endpoint: "http://127.0.0.1:9090/v1/graphql", }, }, diff --git a/pkg/logging/logging.go b/pkg/logging/logging.go index 51604f7..3dd3d40 100644 --- a/pkg/logging/logging.go +++ b/pkg/logging/logging.go @@ -1,6 +1,7 @@ package logging import ( + "fmt" stdlog "log" "os" "time" @@ -65,8 +66,8 @@ func log(contextLog *zerolog.Event, message string, v ...map[string]interface{}) if len(v) > 0 { for _, m := range v { for k, v := range m { - if !pandati.IsZero(v) { - contextLog.Str(k, v.(string)) + if !pandati.IsZero(v) && !pandati.IsZero(k) { + contextLog.Str(k, fmt.Sprintf("%v", v)) } } } diff --git a/query.go b/query.go index 81491a6..4fa376f 100644 --- a/query.go +++ b/query.go @@ -4,7 +4,9 @@ import ( "bytes" "errors" "fmt" + "io" "io/ioutil" + "net/http" "github.com/lukaszraczylo/pandati" ) @@ -21,7 +23,7 @@ type queryResults struct { } `json:"errors"` } -func (g *connHandler) queryBuilder(queryContent string, queryVariables interface{}) ([]byte, error) { +func (g *GraphQL) queryBuilder(queryContent string, queryVariables interface{}) ([]byte, error) { var qb = &requestBase{ Query: queryContent, Variables: queryVariables, @@ -40,18 +42,25 @@ func (g *connHandler) queryBuilder(queryContent string, queryVariables interface return j2, err } -func (g *connHandler) Query(queryContent string, queryVariables interface{}) (responseContent string, err error) { +func (g *GraphQL) Query(queryContent string, queryVariables interface{}, queryHeaders map[string]interface{}) (responseContent string, err error) { g.Log.Debug("Query details", map[string]interface{}{"_query": queryContent, "_variables": queryVariables}) query, err := g.queryBuilder(queryContent, queryVariables) if err != nil { g.Log.Error("Unable to build the query", map[string]interface{}{"_error": err.Error()}) return "", err } - httpResponse, err := g.HttpClient.Post(g.Endpoint, "application/json", bytes.NewBuffer(query)) + httpRequest, err := http.NewRequest("POST", g.Endpoint, bytes.NewBuffer(query)) + httpRequest.Header.Add("Content-Type", "application/json") + for header, value := range queryHeaders { + httpRequest.Header.Add(fmt.Sprintf("%v", header), fmt.Sprintf("%v", value)) + } + + httpResponse, err := g.HttpClient.Do(httpRequest) if err != nil { g.Log.Error("Unable to send the query", map[string]interface{}{"_error": err.Error()}) return "", err } + defer io.Copy(ioutil.Discard, httpResponse.Body) defer httpResponse.Body.Close() body, err := ioutil.ReadAll(httpResponse.Body) @@ -68,7 +77,7 @@ func (g *connHandler) Query(queryContent string, queryVariables interface{}) (re if !pandati.IsZero(queryResult.Errors) { g.Log.Error("Query returned error", map[string]interface{}{"_query": queryContent, "_variables": queryVariables, "_error": fmt.Sprintf("%v", queryResult.Errors)}) - return "", errors.New(fmt.Sprintf("%v", queryResult.Errors[0].Message)) + return "", fmt.Errorf("%v", queryResult.Errors[0].Message) } if pandati.IsZero(queryResult.Data) { diff --git a/query_bench_test.go b/query_bench_test.go index 25d2adb..72a1d74 100644 --- a/query_bench_test.go +++ b/query_bench_test.go @@ -4,7 +4,7 @@ import ( "testing" ) -func Benchmark_connHandler_Query(t *testing.B) { +func Benchmark_GraphQL_Query(t *testing.B) { type args struct { queryContent string queryVariables interface{} @@ -58,7 +58,7 @@ func Benchmark_connHandler_Query(t *testing.B) { server, serverURL := mockGraphQLServerResponses(tt.mockedReply) g.Endpoint = serverURL for n := 0; n < t.N; n++ { - g.Query(tt.args.queryContent, tt.args.queryVariables) + g.Query(tt.args.queryContent, tt.args.queryVariables, nil) } server.Close() }) diff --git a/query_test.go b/query_test.go index 31049bb..95a6ba8 100644 --- a/query_test.go +++ b/query_test.go @@ -7,7 +7,7 @@ import ( "github.com/stretchr/testify/assert" ) -func (suite *TestSuite) Test_connHandler_queryBuilder() { +func (suite *TestSuite) Test_GraphQL_queryBuilder() { type args struct { queryContent string queryVariables interface{} @@ -49,7 +49,7 @@ func (suite *TestSuite) Test_connHandler_queryBuilder() { } } -func (suite *TestSuite) Test_connHandler_Query() { +func (suite *TestSuite) Test_GraphQL_Query() { type args struct { queryContent string queryVariables interface{} @@ -99,7 +99,7 @@ func (suite *TestSuite) Test_connHandler_Query() { os.Setenv("GRAPHQL_ENDPOINT", tt.endpoint) } g := NewConnection() - gotResult, gotErr := g.Query(tt.args.queryContent, tt.args.queryVariables) + gotResult, gotErr := g.Query(tt.args.queryContent, tt.args.queryVariables, nil) if tt.wantErr { assert.Error(t, gotErr) }