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

Kar*_*lek 5 go

我在我的应用程序中使用 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。

Kar*_*lek 9

实际上看起来相当简单。来自这篇博文

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)

  • 通过清理部分中的“req.Context().Err()”来捕获上下文取消的原因也很有用。 (3认同)