英文:
transport.Roundtrip context canceled error
问题
我在客户端进行了一次往返,并设置了1次重试。问题是有时我的客户端触发了"上下文取消",整个处理过程似乎在300毫秒内结束,但我没有设置超时。它是如何触发的?
func RoundTrip(req *http.Request)(res *http.Response, err error){
for i:=0; i<1; i++ {
transport = http.DefaultTransport
res, err = transport.RoundTrip(req)
if err == nil {
break;
}
}
return
}
英文:
I made a roundtrip in client, and I set a retry for 1 time. Question is sometimes my client triggered "context canceled", and entire processing seems like end in 300ms, but I didn't set a timeout. how is it triggered?
func RoundTrip(req *http.Request)(res *http.Response, err error){
for i:=0; i<1; i++ {
transport = http.DefaultTransport
res, err = transport.RoundTrip(req)
if err == nil {
break;
}
}
return
}
答案1
得分: 1
你可以使用Request.WithContext方法或NewRequestWithContext函数将上下文添加到请求中。当你取消上下文时,它应该传播到处理请求的所有函数。
更新
抱歉,我以为你想取消请求,而不是询问为什么。无论如何,根据你对这个答案的评论:
> 但是在300毫秒内取消了上下文
300毫秒的时间非常短。如果时间更长,我会建议调整net.DefaultTransport
中的定时器;然而,我猜测底层的TCP连接被拒绝/限制,导致RoundTrip失败。TCP限制可能是内部问题(DNS查找错误等)或服务器端的问题。你需要更详细地确定问题的范围来进行调试。
英文:
You can add the context to the request with the Request.WithContext method or NewRequestWithContext function. When you cancel the context it should propagate to all functions handling the request.
Update
Sorry I thought you wanted to cancel the request, not asking why. Anyhow given your comment on this answer:
> but where canceled the context in 300ms
300ms is pretty short. If it was longer I would recommend adjusting the timers in net.DefaultTransport
; however, instead I would guess that the underlying TCP connection is being refused/limited and causing the RoundTrip to fail. TCP limit could be something internal (DNS lookup error, etc) or on the server side. You would need to scope the problem more to debug.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论