tr := &http.Transport{
TLSClientConfig: &tls.Config{InsecureSkipVerify: true},
}
client := &http.Client{Transport: tr}
response, err := client.Get(link)
if err != nil {
fmt.Println(err)
}
defer response.Body.Close()
//block forever at the next line
content, _ = ioutil.ReadAll(response.Body)
Run Code Online (Sandbox Code Playgroud)
以上是我的代码,用于从循环中的网页中读取内容.我发现有时这条线ioutil.ReadAll(response.Body)
会永远阻挡.这是随机发生的,然而,它几乎总是发生在这个网页上:http://xkcd.com/55
.非常有趣的是,当我这样做时curl http://xkcd.com/55
,它什么都不返回,然而,wget http://xkcd.com/55
返回整个网页.
在 http.Client 中设置的超时和在请求上下文中设置的超时有什么区别?
我见过 2 种在 http 客户端设置超时的方法。
第一的:
ctx, cancel := context.WithTimeout(context.Background(), 2*time.Second)
defer cancel()
req, err := http.NewRequestWithContext(ctx, http.MethodGet, "http://localhost:8080", nil)
Run Code Online (Sandbox Code Playgroud)
第二:
client := http.Client{
Timeout: 2 * time.Second,
}
resp, err := client.Do(req)
if err != nil {
panic(err)
}
Run Code Online (Sandbox Code Playgroud)
什么时候使用一个?