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

set logger to intercept raw request and reply data #79

Open
wants to merge 1 commit into
base: main
Choose a base branch
from
Open
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
13 changes: 13 additions & 0 deletions graphql.go
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ import (
"context"
"encoding/json"
"fmt"
"io"
"io/ioutil"
"net/http"

Expand All @@ -16,6 +17,7 @@ import (
type Client struct {
url string // GraphQL server URL.
httpClient *http.Client
logger io.Writer
}

// NewClient creates a GraphQL client targeting the specified GraphQL server URL.
Expand All @@ -30,6 +32,11 @@ func NewClient(url string, httpClient *http.Client) *Client {
}
}

// SetLogger set verbose logger
func (c *Client) SetLogger(l io.Writer) {
c.logger = l
}

// Query executes a single GraphQL query request,
// with a query derived from q, populating the response into it.
// q should be a pointer to struct that corresponds to the GraphQL schema.
Expand Down Expand Up @@ -65,6 +72,9 @@ func (c *Client) do(ctx context.Context, op operationType, v interface{}, variab
if err != nil {
return err
}
if c.logger != nil {
c.logger.Write(append([]byte("request:\n\t"), buf.Bytes()...))
}
resp, err := ctxhttp.Post(ctx, c.httpClient, c.url, "application/json", &buf)
if err != nil {
return err
Expand All @@ -85,6 +95,9 @@ func (c *Client) do(ctx context.Context, op operationType, v interface{}, variab
return err
}
if out.Data != nil {
if c.logger != nil {
c.logger.Write(append([]byte("reply:\n\t"), (*out.Data)...))
}
err := jsonutil.UnmarshalGraphQL(*out.Data, v)
if err != nil {
// TODO: Consider including response body in returned error, if deemed helpful.
Expand Down