可以使用Google的API Go库来自定义HTTP客户端。

huangapple go评论86阅读模式
英文:

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

问题

为了使用Google的API go SDK,我们需要使用token source。这在单独使用时效果很好,但在使用自定义HTTP客户端时会遇到问题。

文档确实提到,在使用自定义HTTP客户端时,选项不会被保留。但这对我们来说是必要的,以便对我们的客户端进行仪表化。

有没有办法同时使用HTTP客户端和token source?

英文:

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?

答案1

得分: 1

因为WithHTTPClient排除了使用其他选项的可能性,所以替代方案是使用令牌源准备HTTP客户端。为了实现这一点,需要定义传输方式。

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

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,
		},
	}),
)

huangapple
  • 本文由 发表于 2021年11月16日 01:28:45
  • 转载请务必保留本文链接:https://go.coder-hub.com/69978463.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定