可以使用以下简单的 go 代码片段重现该问题吗?
简单的 http 服务器:
package main
import (
"fmt"
"log"
"net/http"
"time"
)
func handler(w http.ResponseWriter, r *http.Request) {
go func(done <-chan struct{}) {
<-done
fmt.Println("message", "client connection has gone away, request got cancelled")
}(r.Context().Done())
time.Sleep(30 * time.Second)
fmt.Fprintf(w, "Hi there, I love %s!\n", r.URL.Path[1:])
}
func main() {
http.HandleFunc("/", handler)
log.Fatal(http.ListenAndServe(":8080", nil))
}
Run Code Online (Sandbox Code Playgroud)
从 http 服务器上方开始,如果我GET使用 curl(邮递员也)发送一个简单的请求,例如:
curl -X GET http://localhost:8080/
Run Code Online (Sandbox Code Playgroud)
然后按Ctrl+C终止请求,然后我就可以在服务器端看到打印的消息:
message client connection has gone away, request got cancelled
Run Code Online (Sandbox Code Playgroud)
以上是我期望的正确行为:模拟当客户端离开时服务器可以捕获它然后尽早取消所有不必要的工作的情况。 …