Go 设置内置HTTP请求超时的最佳方法
在内置的http NewRequest上设置超时的最佳方法是什么?目前,我使用的是覆盖整个交换的Go 设置内置HTTP请求超时的最佳方法,go,timeout,Go,Timeout,在内置的http NewRequest上设置超时的最佳方法是什么?目前,我使用的是覆盖整个交换的http.Client.Timeout,但是否有更好的方法,例如context.WithDeadline或context.WithTimeout。如果是,它是如何工作的,我如何为http.NewRequest设置context.WithDeadline解决方案 我目前的解决方案是: func (c *Client) post(resource string, data url.Values, time
http.Client
.Timeout,但是否有更好的方法,例如context.WithDeadline
或context.WithTimeout
。如果是,它是如何工作的,我如何为http.NewRequest
设置context.WithDeadline
解决方案
我目前的解决方案是:
func (c *Client) post(resource string, data url.Values, timeout time.Duration) ([]byte, error) {
url := c.getURL(resource)
client := &http.Client{
Timeout: timeout * time.Millisecond,
}
req, err := http.NewRequest("POST", url, strings.NewReader(data.Encode()))
if err != nil {
return nil, err
}
req.Header.Add("Content-Type", "application/x-www-form-urlencoded")
resp, err := client.Do(req)
if err != nil {
return nil, err
}
return ioutil.ReadAll(resp.Body)
}
从context.withDaildate获取新上下文。看见 WithTimeout只返回WithDeadline(父级,time.Now().Add(timeout)) 如果要在main上执行取消触发器:
func main() {
ctx := context.Background()
ctx, cancel := context.WithCancel(ctx)
sc := make(chan os.Signal, 1)
signal.Notify(sc, os.Interrupt)
go func(){
<-sc
cancel()
}()
getContent(ctx)
}
func main(){
ctx:=context.Background()
ctx,cancel:=上下文。带取消(ctx)
sc:=制造(转换操作信号,1)
信号通知(sc、os中断)
go func(){
我不理解反对WithTimeout
的论点。它正是OP想要的,很清楚它是做什么的,为什么不直接使用它,而不是使用WithDeadline
内联重写它呢?我写这篇文章是因为OP想要。
func main() {
ctx := context.Background()
ctx, cancel := context.WithCancel(ctx)
sc := make(chan os.Signal, 1)
signal.Notify(sc, os.Interrupt)
go func(){
<-sc
cancel()
}()
getContent(ctx)
}