gpt4 book ai didi

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

转载 作者:数据小太阳 更新时间:2023-10-29 03:12:10 26 4
gpt4 key购买 nike

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

这是我的示例代码:

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 fetched\n", 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()

这样,您将得到一个 nil resp(和一个错误),并在超时时断开连接。

关于http - 在 golang X ms 之后以编程方式关闭 http 连接,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48597109/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com