登录
首页 >  Golang >  Go问答

利用request.Context替代CloseNotifier的方式是什么?

来源:stackoverflow

时间:2024-03-24 19:18:35 201浏览 收藏

在应用程序中使用 `closenotifier` 现已弃用,建议使用 `request.Context` 替代。通过使用 `request.Context`,可以更方便地处理客户端断开连接的情况。在原代码中,`closenotifier` 用来检测客户端断开连接,而现在可以使用 `request.Context` 的 `Done()` 通道来实现同样的功能。

问题内容

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

func handler(res http.resonsewriter, req *http.request) {
    notify := res.(closenotifier).closenotify()

    somelogic();
    select {
        case <-notify:
            somecleanup()
            return;
        default:
    }
    someotherlogic();
}

我注意到 closenotifier 现已弃用。来自源代码:

// 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();
}

以上就是本文的全部内容了,是否有顺利帮助你解决问题?若是能给你带来学习上的帮助,请大家多多支持golang学习网!更多关于Golang的相关知识,也可关注golang学习网公众号。

声明:本文转载于:stackoverflow 如有侵犯,请联系study_golang@163.com删除
相关阅读
更多>
最新阅读
更多>
课程推荐
更多>