英文:
The network is slowing down the request or reading the response body
问题
我正在编写一个客户端。哪个操作应该受到超时保护?是获取请求 resp, err := http.Get(fileURL)
还是读取响应体 n, err = resp.Body.Read(chunk)
。这两个操作中哪个可能受到网络的影响?
英文:
I'm writing a client. What action should be protected by timeout? Get request resp, err := http.Get(fileURL)
or read the response body n, err = resp.Body.Read(chunk)
. Which of these actions can be affected by the network?
答案1
得分: 1
最简单的形式将涵盖拨号和读取响应体的超时时间(如果连接不被重用)。
c := &http.Client{
Timeout: 15 * time.Second,
}
resp, err := c.Get("https://foo.bar/")
这些是我所了解的所有HTTP客户端超时设置。
c := &http.Client{
Transport: &http.Transport{
Dial: (&net.Dialer{
Timeout: 30 * time.Second,
KeepAlive: 30 * time.Second,
}).Dial,
TLSHandshakeTimeout: 10 * time.Second,
ResponseHeaderTimeout: 10 * time.Second,
ExpectContinueTimeout: 1 * time.Second,
},
}
resp, err := c.Get("https://foo.bar/")
英文:
The simplest form will cover the timeout for the dial and reading the body. (If a connection is not reused)
c := &http.Client{
Timeout: 15 * time.Second,
}
resp, err := c.Get("https://foo.bar/")
These are all http client timeouts I know.
c := &http.Client{
Transport: &http.Transport{
Dial: (&net.Dialer{
Timeout: 30 * time.Second,
KeepAlive: 30 * time.Second,
}).Dial,
TLSHandshakeTimeout: 10 * time.Second,
ResponseHeaderTimeout: 10 * time.Second,
ExpectContinueTimeout: 1 * time.Second,
}
}
resp, err := c.Get("https://foo.bar/")
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论