每当来自客户端的 Web 请求传入时,它都会生成一个 goroutine 来处理每个请求。如果客户端恰好断开连接,Web 服务器是否有可能关闭该特定 goroutine,或者该 goroutine 是否会在执行完所有代码后发现客户端已经断开连接?
最佳答案
除了在读取或写入错误时从调用的处理程序返回时退出 - 执行的 go 例程不会自动处理清理运行时间较长的操作,但 Go 提供了处理此问题的好方法。
首先,如果您不熟悉 context package - 这是一种将 go 例程与取消行为同步的强大且惯用的方法,我强烈建议阅读博客 Go Concurrency Patterns: Context .
类似下面的内容:
func MyServiceFunc(ctx context.Context) {
for {
select {
case <-ctx.Done():
break
default:
//do work
}
}
}
func MyRequestHandler(res http.ResponseWriter, req *http.Request) {
MyServiceFunc(req.Context())
//write response...
}
或者您可以使用 CloseNotifier其中一个接口(interface) http.ResponseWriter也实现了,你可以像下面这个简单的例子那样做:
func MyServiceFunc(notifier <-chan bool) {
for {
select {
case <-notifier:
break
default:
//do work
}
}
}
func MyRequestHandler(res http.ResponseWriter, req *http.Request) {
notifier := res.(http.CloseNotifier).CloseNotify()
MyServiceFunc(notifier)
//write response...
}
或者,结合使用这两种方法的简单示例:
func MyRequestHandler(res http.ResponseWriter, req *http.Request) {
notifier := res.(http.CloseNotifier).CloseNotify()
ctx, cancel := context.WithCancel(req.Context())
go func(closer <-chan bool) {
<-closer //the notifer blocks until the send
cancel() //explicitly cancel all go routines
}(notifier)
go MyServiceFunc(ctx)
MyOtherServiceFunc(ctx)
//write response...
}
关于rest - Goroutine 已经根据请求在 Go Web 服务器中启动,但客户端断开连接,Web 服务器是否可以关闭该特定的 goroutine?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51031631/