douweng3564 2019-02-26 17:13
浏览 90
已采纳

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

I am using CloseNotifier in my application, in a code that looks like this

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

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

I have noticed CloseNotifier is now deprecated. From source code:

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

However, I am not sure how to use Request.Context exactly here.

  • 写回答

1条回答 默认 最新

  • doudun5009 2019-02-26 17:17
    关注

    It seems rather simple actually. 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();
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 (标签-STM32|关键词-智能小车)
  • ¥20 关于#stm32#的问题,请各位专家解答!
  • ¥15 (标签-python)
  • ¥20 搭建awx,试了很多版本都有错
  • ¥15 java corba的客户端该如何指定使用本地某个固定IP去连接服务端?
  • ¥15 activiti工作流问题,求解答
  • ¥15 有人写过RPA后台管理系统么?
  • ¥15 Bioage计算生物学年龄
  • ¥20 如何将FPGA Alveo U50恢复原来出厂设置哇?
  • ¥50 cocos2d-x lua 在mac上接入lua protobuf?