Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to copy Context object without deriving

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.

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.

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.

like image 924
Mr. Nicky Avatar asked Dec 15 '19 22:12

Mr. Nicky


Video Answer


1 Answers

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 }

Use it like this:

 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.

like image 100
2 revs Avatar answered Sep 18 '22 18:09

2 revs