简体   繁体   中英

Is converting byte slice to context possible?

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.Context is an interface, the implementations provided by the standard library do not support marshaling the value. For example context.WithValue() returns a context implementation (unexported *context.valueCtx type) 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.Context is 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM