Go语言中Context的使用与实践
1. Request Cancellation
在使用 http.Client 执行HTTP请求时, context 的一个很好的用途是进行请求的取消和超时处理。 http.Client 可以自动处理来自 context 的中断。
以下是一个示例代码:
func main() {
const addr = "localhost:8080"
http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
time.Sleep(time.Second * 5)
})
go func() {
if err := http.ListenAndServe(addr, nil); err != nil {
log.Fatalln(err)
}
}()
req, _ := http.NewRequest(http.MethodGet, "http://"+addr, nil)
ctx, canc := context.WithTimeout(context.Background(), time.Second*2)
defer canc()
time.Sleep(time.Second)
if _, err := http.DefaultClient.Do(req.W
超级会员免费看
订阅专栏 解锁全文
1245

被折叠的 条评论
为什么被折叠?



