http.Client设置的超时时间和请求上下文中设置的超时时间有什么区别?
我看到过两种在http client中设置超时时间的方法。
第一种:
ctx, cancel := context.WithTimeout(context.Background(), 2*time.Second)
defer cancel()
req, err := http.NewRequestWithContext(ctx, http.MethodGet, "http://localhost:8080", nil)
其次:
client := http.Client{
Timeout: 2 * time.Second,
}
resp, err := client.Do(req)
if err != nil {
panic(err)
}
何时使用其中之一而不是另一个?