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

查看:839
本文介绍了Golang:如何在不派生的情况下复制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.

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

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