douzheng1853 2019-01-10 12:33
浏览 92
已采纳

没有取消传播的上下文

How can I create a copy (a clone if you will) of a Go context that contains all of the values stored in the original, but does not get canceled when the original does?

It does seem like a valid use case to me. Say I have an http request and its context is canceled after the response is returned to a client and I need to run an async task in the end of this request in a separate goroutine that will most likely outlive the parent context.

func Handler(ctx context.Context) (interface{}, error) {
        result := doStuff(ctx)
        newContext := howDoICloneYou(ctx)
        go func() {
                doSomethingElse(newContext)
        }()
        return result
}

Can anyone advice how this is supposed to be done?

Of course I can keep track of all the values that may be put into the context, create a new background ctx and then just iterate through every possible value and copy... But that seems tedious and is hard to manage in a large codebase.

  • 写回答

2条回答 默认 最新

  • dongxi1680 2019-01-10 15:51
    关注

    Since context.Context is an interface, you can simply create your own implementation that is never canceled:

    import (
        "context"
        "time"
    )
    
    type noCancel struct {
        ctx context.Context
    }
    
    func (c noCancel) Deadline() (time.Time, bool)       { return time.Time{}, false }
    func (c noCancel) Done() <-chan struct{}             { return nil }
    func (c noCancel) Err() error                        { return nil }
    func (c noCancel) Value(key interface{}) interface{} { return c.ctx.Value(key) }
    
    // WithoutCancel returns a context that is never canceled.
    func WithoutCancel(ctx context.Context) context.Context {
        return noCancel{ctx: ctx}
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 对于这个复杂问题的解释说明
  • ¥50 三种调度算法报错 采用的你的方案
  • ¥15 关于#python#的问题,请各位专家解答!
  • ¥200 询问:python实现大地主题正反算的程序设计,有偿
  • ¥15 smptlib使用465端口发送邮件失败
  • ¥200 总是报错,能帮助用python实现程序实现高斯正反算吗?有偿
  • ¥15 对于squad数据集的基于bert模型的微调
  • ¥15 为什么我运行这个网络会出现以下报错?CRNN神经网络
  • ¥20 steam下载游戏占用内存
  • ¥15 CST保存项目时失败