我在我的应用程序中使用 CloseNotifier,代码如下所示
func Handler(res http.ResonseWriter, req *http.Request) {
notify := res.(CloseNotifier).CloseNotify()
someLogic();
select {
case <-notify:
someCleanup()
return;
default:
}
someOtherLogic();
}
Run Code Online (Sandbox Code Playgroud)
我注意到 CloseNotifier 现在已被弃用。从源代码:
// Deprecated: the CloseNotifier interface predates Go's context package.
// New code should use Request.Context instead.
Run Code Online (Sandbox Code Playgroud)
但是,我不确定如何在这里使用 Request.Context。
实际上看起来相当简单。来自这篇博文:
func Handler(res http.ResonseWriter, req *http.Request) {
ctx := req.Context()
someLogic();
select {
case <-ctx.Done():
someCleanup(ctx.Err())
return;
default:
}
someOtherLogic();
}
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
967 次 |
最近记录: |