如何为idtoken.NewClient设置超时选项?

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

How to set timeout option for idtoken.NewClient

问题

我正在使用Google的idtoken.NewClient从我的GCP获取一些信息。由于请求时间太长,我需要设置一个超时时间。我尝试像这样设置它:

var netClient = &http.Client{
    Timeout:   time.Second * 10,
    Transport: http.DefaultTransport,
}

options := idtoken.WithHTTPClient(netClient)

// client is a http.Client that automatically adds an "Authorization" header
// to any requests made.
client, err := idtoken.NewClient(ctx, targetURL, options)

但是我遇到了以下错误:
idtoken.NewClient: transport/http: WithHTTPClient passed to NewTransport

我不知道如何设置这个选项。

英文:

I'm using googles idtoken.NewClient to get some information from my gcp. I need to set a timeout because the request takes too long. I tried to set it up like this

		Timeout: time.Second * 10,
		Transport: http.DefaultTransport,
	}

	options := idtoken.WithHTTPClient(netClient)

	// client is a http.Client that automatically adds an "Authorization" header
	// to any requests made.
	client, err := idtoken.NewClient(ctx, targetURL, options)

but I am getting theq follwoing error:
idtoken.NewClient: transport/http: WithHTTPClient passed to NewTransport

I don't know how to set this option

答案1

得分: 1

当一个函数接受上下文(context)时,它应该能够优雅地处理取消操作。这意味着你可以使用WithTimeout将上下文包装起来,在给定的时间段后取消它,例如:

timeout, cancel := context.WithTimeout(ctx, 10 * time.Second)
defer cancel()
client, err := idtoken.NewClient(timeout, targetURL, options))
英文:

When a function accepts context, it's expected to handle its cancellation gracefully. That means, you can wrap the context with WithTimeout, so that it will get cancelled after the given duration of time, e.g.:

timeout, cancel := context.WithTimeout(ctx, 10 * time.Second)
defer cancel()
client, err := idtoken.NewClient(timeout, targetURL, options))

huangapple
  • 本文由 发表于 2021年9月9日 20:42:07
  • 转载请务必保留本文链接:https://go.coder-hub.com/69118396.html
匿名

发表评论

匿名网友

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

确定