英文:
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))
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。


评论