这是来自 golang 上下文页面https://blog.golang.org/context的代码片段
func httpDo(ctx context.Context, req *http.Request, f func(*http.Response, error) error) error {
// Run the HTTP request in a goroutine and pass the response to f.
c := make(chan error, 1)
req = req.WithContext(ctx)
go func() { c <- f(http.DefaultClient.Do(req)) }()
select {
case <-ctx.Done():
<-c // Wait for f to return.
return ctx.Err()
case err := <-c:
return err
}
}
这种方法的描述说
httpDo 函数运行 HTTP 请求并在新的 goroutine 中处理其响应。如果 ctx.Done 在 goroutine 退出之前关闭,它将取消请求:
这里的请求是如何取消的?在我看来,即使上下文完成,我们仍在等待请求的结果?这有什么帮助?
MMTTMM
慕田峪9158850
相关分类