Go 上下文超时请求
示例
1.7+
使用上下文超时HTTP请求只能使用1.7+中的标准库(而不是子仓库)来完成:
import (
"context"
"net/http"
"time"
)
req, err := http.NewRequest("GET", `https://example.net`, nil)
ctx, _ := context.WithTimeout(context.TODO(), 200 * time.Milliseconds)
resp, err := http.DefaultClient.Do(req.WithContext(ctx))
//确保处理错误。
defer resp.Body.Close()1.7之前
import (
"net/http"
"time"
"golang.org/x/net/context"
"golang.org/x/net/context/ctxhttp"
)
ctx, err := context.WithTimeout(context.TODO(), 200 * time.Milliseconds)
resp, err := ctxhttp.Get(ctx, http.DefaultClient, "https://www.example.net")
//确保处理错误。
defer resp.Body.Close()进一步阅读
有关该context软件包的更多信息,请参见上下文。