Goroutine 已经根据请求在 Go Web 服务器中启动,但客户端断开连接,Web 服务器是否有可能关闭该特定 Goroutine?

Ric*_*ow3 0 rest webserver web-services go goroutine

每当来自客户端的 Web 请求传入时,它都会生成一个 goroutine 来处理每个请求。如果客户端恰好与连接断开连接,Web 服务器是否有可能关闭该特定 goroutine,或者该 goroutine 在执行完所有代码后是否会发现客户端已经断开连接?

syl*_*bix 5

除了在读取或写入错误时从被调用的处理程序返回时退出 - 正在执行的 go 例程不会自动处理清理长时间运行的操作,但 Go 提供了很好的处理方法。

首先,如果您不熟悉context 包- 它是一种将 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...
}
Run Code Online (Sandbox Code Playgroud)

或者您可以使用http.ResponseWriter也实现的CloseNotifier接口,您可以执行类似于以下简单示例的操作:

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...
}
Run Code Online (Sandbox Code Playgroud)

或者,使用结合两种方法的简单示例:

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...
}
Run Code Online (Sandbox Code Playgroud)