gogoogle-analytics-apigoogle-analytics-4google-api-go-client

Use custom HTTP client with Google's API go library?


In order to make use of Google's API go SDK, we need to make use of the token source. This works great on its own, but becomes a problem when using a custom HTTP client.

The documentation does mention that options are not preserved when making use of a custom HTTP client. This is necessary for us in order to instrument our client.

Is there a way to make use of an HTTP client and a token source at the same time?


Solution

  • Because WithHTTPClient rules out the use of any other option, the alternative is to prepare the http client with the token source. To achieve that, the transport needs to be defined.

    service, err := ggoauth2.NewService(
        ctx,
        option.WithHTTPClient(&http.Client{
            Timeout: 30 * time.Second,
            Transport: &oauth2.Transport{
                Base:   http.DefaultTransport,
                Source: tokenSource,
            },
        }),
    )