machinebox / graphql

Simple low-level GraphQL HTTP client for Go
https://blog.machinebox.io/a-graphql-client-library-for-go-5bffd0455878
Apache License 2.0
933 stars 217 forks source link

[QUESTION] How to print/return raw response from graphql server? #71

Open bynov opened 2 years ago

bynov commented 2 years ago

Hi!

I see errors

decoding response: json: cannot unmarshal string into Go struct field graphResponse.Errors of type graphql.graphErr

So, how I can easily print raw response without changing the library?

adambabik commented 2 years ago

It's not trivial... but it's possible. I use this technique for many libraries that don't provide an interface to do it.

  1. Create a custom http.Client,
  2. Specify http.RoundTripper that will log HTTP request and responses,
  3. Create graphql.Client with a custom http.Client.

The most tricky one is (2):

// "github.com/henvic/httpretty"
logger := &httpretty.Logger{}
httpClient = &http.Client{
    Transport: logger.RoundTripper(http.DefaultTransport),
}
gqlClient := graphql.NewClient(endpoint, graphql.WithHTTPClient(httpClient))
adambabik commented 2 years ago

Oh, I just discovered there is a simpler way: gqlClient.Log = func(s string) { log.Println(s) }