在 golang 中的 X ms 之后以编程方式关闭 http 连接



我正在执行 X 个并行 http 请求,当其中一个在 X 毫秒(想象一下是 100 毫秒(或更短的时间内没有响应时,我想切断这个连接。我写的代码似乎不起作用,我怎样才能切断连接并获得零响应?

这是我的示例代码:

cx, cancel := context.WithCancel(context.Background())
ch := make(chan *HttpResponse)
var responses []*HttpResponse
timeout := 1.000 //1ms for testing purposes
var client = &http.Client{
    Timeout: 1 * time.Second,
}
startTime := time.Now()
for _, url := range urls {
    go func(url string) {
        fmt.Printf("Fetching %s n", url)
        req, _ := http.NewRequest("POST", url, bytes.NewReader(request)) //request is json string
        req.WithContext(cx)
        resp, err := client.Do(req)
        ch <- &HttpResponse{url, resp, err}
        var timeElapsed = time.Since(startTime)
        msec := timeElapsed.Seconds() * float64(time.Second/time.Millisecond)
        if msec >= timeout {
            cancel()
        }
        if err != nil && resp != nil && resp.StatusCode == http.StatusOK {
            resp.Body.Close()
        }
    }(url)
}
for {
    select {
    case r := <-ch:
        fmt.Printf("%s was fetchedn", r.Url)
        if r.Err != nil {
            fmt.Println("with an error", r.Err)
        }
        responses = append(responses, r)
        if len(responses) == len(*feeds) {
            return responses
        }
    case <-time.After(100):
        //Do something
    }
}

您的代码会等到请求完成(并得到响应或错误(,然后计算经过的时间,如果它比预期的时间长,您的代码将取消所有请求。

    req, _ := http.NewRequest("POST", url, bytes.NewReader(request)) //request is json string
    req.WithContext(cx) //Here you use a common cx, which all requests share.
    resp, err := client.Do(req) //Here the request is being sent and you wait it until done.
    ch <- &HttpResponse{url, resp, err}
    var timeElapsed = time.Since(startTime)
    msec := timeElapsed.Seconds() * float64(time.Second/time.Millisecond)
    if msec >= timeout {
        cancel() //here you cancel all the requests.
    }

解决方法是正确利用context包。

    req, _ := http.NewRequest("POST", url, bytes.NewReader(request)) //request is json string
    ctx,cancel := context.WithTimeout(request.Context(),time.Duration(timeout)*time.Millisecond)
    resp,err:=client.Do(req.WithContext(ctx))
    defer cancel()

这样,您将获得零resp(和错误(,并在超时时切断连接。

相关内容

  • 没有找到相关文章

最新更新