如何在不派生的情况下复制Context对象 [英] How to copy Context object without deriving

查看:159
本文介绍了如何在不派生的情况下复制Context对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想复制一个上下文对象-确切地说是一个请求上下文,并稍后在一个单独的go例程中使用它.

I want to make a copy of a context object - a request context to be exact, and make use of it later on in a separate go routine.

问题是如果此请求的HTTP处理程序完成后,如果我使用 context.WithCancel(reqCtx)派生请求上下文,则不仅原始请求上下文将被取消,而且该请求的副本也将被取消请求上下文也将被取消.

Problem is if I derive the request context using context.WithCancel(reqCtx) once the HTTP handler for this request is finished, not only will the original request context be cancelled, but also the copy of the request context will also be canceled.

我希望能够复制原始请求上下文,而不希望在HTTP处理程序执行完后被原始上下文取消.

I'd like to be able to copy the original request context and not have it canceled by the original context after the HTTP handler has finished executing.

推荐答案

以下是创建一个使用其他上下文中的值但未取消的值的上下文的方法:

Here's how to make a context that uses values from some other context, but not cancelation:

type valueOnlyContext struct{ context.Context }
func (valueOnlyContext) Deadline() (deadline time.Time, ok bool) { return }
func (valueOnlyContext) Done() <-chan struct{} { return nil }
func (valueOnlyContext) Err() error { return nil }

像这样使用它:

 ctx := valueOnlyContext{reqCtx}

使用这些值而不进行取消可能超出了上下文包的设计意图.如果程序包的设计者认为这是一件好事,我希望他们将以上内容捆绑到上下文程序包功能中.

Using the values without cancelation is probably outside the design intent of the context package. If the designers of the package thought this is a good thing, I would have expected them to bundle up the above in a context package function.

这篇关于如何在不派生的情况下复制Context对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆