I have an application that consumes messages from beanstalkd. You cannot pass context to beanstalkd and you can only use byte slice to send messages. So I converted my context to byte slice.
To propagate from passed context it needs to be converted to context.Context. Is this possible?
// Sending context
ctx := context.Background()
reqBodyBytes := new(bytes.Buffer)
json.NewEncoder(reqBodyBytes).Encode(ctx)
_, err = conn.Put(reqBodyBytes.Bytes(), 1, 0, 120*time.Second)
// Consuming context
_, body, err := conn.Reserve(120 * time.Second)
fmt.Println(string(body))
In general it is not possible.
context.Contextis an interface, the implementations provided by the standard library do not support marshaling the value. For examplecontext.WithValue()returns a context implementation (unexported*context.valueCtxtype) that stores the key-value pair in unexported fields.But since it is an interface type, you may provide implementations that do provide marshaling and unmarshaling capabilities. Although you might run into difficulties marshaling and unmarshaling values of any type if you want to support the context's
Context.Value()method too.In general this isn't a good idea. A
context.Contextis meant to "carry deadlines, cancellation signals, and other request-scoped values across API boundaries and between processes". It's not something you'd want to persist / transfer.