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 乘性高斯噪声在深度学习网络中的应用
  • ¥15 运筹学排序问题中的在线排序
  • ¥15 关于docker部署flink集成hadoop的yarn,请教个问题 flink启动yarn-session.sh连不上hadoop,这个整了好几天一直不行,求帮忙看一下怎么解决
  • ¥30 求一段fortran代码用IVF编译运行的结果
  • ¥15 深度学习根据CNN网络模型,搭建BP模型并训练MNIST数据集
  • ¥15 C++ 头文件/宏冲突问题解决
  • ¥15 用comsol模拟大气湍流通过底部加热(温度不同)的腔体
  • ¥50 安卓adb backup备份子用户应用数据失败
  • ¥20 有人能用聚类分析帮我分析一下文本内容嘛
  • ¥30 python代码,帮调试,帮帮忙吧