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

标签 rest web-services go webserver goroutine

每当来自客户端的 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/

相关文章:

spring - Grails 3 REST-API匿名访问被ExceptionTranslationFilter拒绝

java - 使用 javax.ws 和 angular 打开 pdf 文件

java - Spring 返回自定义 SOAP 故障

mongodb - 如果slice存在,并且它包含至少一个设置为true的特定变量

xml - 如何从 marshal 重新排序 xml 标签

ruby-on-rails - Rails RESTful 删除嵌套资源

java - RPC/文档编码真实示例

web-services - 返回图像和数字的 Web 服务

pointers - 我如何从golang中的 slice 获取结构指针

web-services - REST API - 如果请求正文的信息超出需要,我是否应该返回错误?