【发布时间】:2018-05-23 09:39:18
【问题描述】:
我有一个这样的 Go HTTP 处理程序:
mux.HandleFunc("/test", func(w http.ResponseWriter, r *http.Request) {
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
if cn, ok := w.(http.CloseNotifier); ok {
go func(done <-chan struct{}, closed <-chan bool) {
select {
case <-done:
case <-closed:
fmt.Println("client cancelled....................!!!!!!!!!")
cancel()
}
}(ctx.Done(), cn.CloseNotify())
}
time.Sleep(5 * time.Second)
fmt.Println("I am still running...........")
fmt.Fprint(w, "cancellation testing......")
})
API 工作正常,然后在请求完成之前使用 curl 我故意用 Control-C 终止 curl 命令,在服务器端我确实看到 client cancelled....................!!!!!!!!! 被注销,但过了一会儿 I am still running........... 得到也注销了,我以为这个goroutine会立即终止!
那么,这是期望的行为,还是我做错了什么?
如果是预期的,既然goroutine会完成它的工作,那么提前取消有什么意义呢?
如果我做错了什么,请帮助指出正确的方法。
【问题讨论】:
标签: http go cancellation