Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/go/7.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Go 设置内置HTTP请求超时的最佳方法_Go_Timeout - Fatal编程技术网

Go 设置内置HTTP请求超时的最佳方法

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 NewRequest上设置超时的最佳方法是什么?目前,我使用的是覆盖整个交换的
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)
}