go - 如何使用 request.Context 而不是 CloseNotifier?

标签 go

我在我的应用程序中使用 CloseNotifier,代码如下所示

func Handler(res http.ResonseWriter, req *http.Request) {
    notify := res.(CloseNotifier).CloseNotify()

    someLogic();
    select {
        case <-notify:
            someCleanup()
            return;
        default:
    }
    someOtherLogic();
}

我注意到 CloseNotifier 现在已被弃用。 From source code :

// Deprecated: the CloseNotifier interface predates Go's context package.
// New code should use Request.Context instead.

但是,我不确定如何在此处使用 Request.Context。

最佳答案

实际上看起来很简单。 From this blogpost :

func Handler(res http.ResonseWriter, req *http.Request) {
    ctx := req.Context()

    someLogic();
    select {
        case <-ctx.Done():
            someCleanup(ctx.Err())
            return;
        default:
    }
    someOtherLogic();
}

关于go - 如何使用 request.Context 而不是 CloseNotifier?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54890809/

相关文章:

go - 从完成 channel 和未关闭 channel 的 GC 生成 context.Context

string - Go中子字符串的字符位置

python - 最初是在 Python 中创建的,如何在 Go 中使用数据存储 GAE?

go - gorilla/context 与 gorilla/sessions 有何不同?

mysql - 如何用MySQL编写golang集成测试

react-native - Heroku 授权 header 丢失

go - 将 Query() 与 Go 客户端一起使用时,Aerospike 随机返回 nil 错误

go - 为 Go 测试设置环境变量

scala - Scala 和 Google 'Go' 语言之间是否有比较(逐个功能)?

json - 编码和解码结构到 json 丢失信息