利用request.Context替代CloseNotifier的方式是什么?
时间:2024-03-24
浏览: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学习网公众号。
本文内容来源于互联网,如有侵权请联系删除。
近期热门
11.18
11.15
站内热门
最新文章
11.20
11.20
11.20
11.20
热门专题
