将字节切片转换为上下文是否可能?

huangapple go评论85阅读模式
英文:

Is converting byte slice to context possible?

问题

我有一个从beanstalkd消费消息的应用程序。你不能将上下文传递给beanstalkd,只能使用字节切片发送消息。所以我将我的上下文转换为字节切片。

要传播传递的上下文,需要将其转换为context.Context。这可能吗?

// 发送上下文
ctx := context.Background()

reqBodyBytes := new(bytes.Buffer)
json.NewEncoder(reqBodyBytes).Encode(ctx)

_, err = conn.Put(reqBodyBytes.Bytes(), 1, 0, 120*time.Second)

// 消费上下文
_, body, err := conn.Reserve(120 * time.Second)
fmt.Println(string(body))
英文:

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))

答案1

得分: 3

通常情况下是不可能的。context.Context 是一个接口,标准库提供的实现不支持对值进行编组。例如,context.WithValue() 返回一个上下文实现(未导出的 *context.valueCtx 类型),它将键值对存储在未导出的字段中。

但是,由于它是一个接口类型,您可以提供支持编组和解组能力的实现。尽管如果您还想支持上下文的 Context.Value() 方法,您可能会遇到对任何类型的值进行编组和解组的困难。

总的来说,这不是一个好主意。context.Context 用于“在 API 边界和进程之间传递截止时间、取消信号和其他请求范围的值”。它不是您希望持久化/传输的内容。

英文:

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.

huangapple
  • 本文由 发表于 2021年11月2日 00:00:48
  • 转载请务必保留本文链接:https://go.coder-hub.com/69799508.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定