我的代码是这样的:
package main
import (
"context"
"fmt"
"io"
"net/http"
"os"
)
var (
client = http.DefaultClient
)
func do(pctx context.Context, req *http.Request) (*http.Response, error) {
// in order to not capture the pctx.Done. the caller may capture the pctx.Done().
ctx, cancel := context.WithCancel(pctx)
defer cancel()
req = req.WithContext(ctx)
resp, err := client.Do(req)
if err != nil {
select {
case <-ctx.Done():
return nil, ctx.Err()
}
}
return resp, err
}
func main() {
req, err := http.NewRequest(http.MethodGet, "http://www.google.com", nil)
if err != nil {
panic(err)
}
resp, err := do(context.Background(), req)
if err != nil {
panic(err)
}
defer resp.Body.Close()
_, err = io.Copy(os.Stdout, resp.Body)
fmt.Println()
fmt.Println()
fmt.Println(err)
}
它输出
$ go run .
<!doctype html><ht[...... removed for conciseness]
context canceled
这段代码是错误的。上下文将取消当我从 resp.Body 读取数据时,我如何取消上下文,在处理 http 请求期间上下文会自动取消吗?谢谢你。