go~context的Value的建议写法
context.Context 是 Go 标准库中用于在不同的函数调用和 goroutine 之间传递请求数据、取消信号以及截止时间等信息的机制。通过 context.WithValue 函数,可以将键值对存储在 Context 中,然后在后续的函数调用中通过 Context.Value 方法来获取这些值。
在 Go 语言里,为了利用 context.Context 来安全地传递和存储特定类型的数据,同时避免键冲突,必须要使用自定义类型作为键
避免键冲突
在多个包或者不同的代码模块中,可能会使用 context.WithValue 来存储不同的数据。如果使用基本数据类型(如 string)作为键,很容易出现键冲突的问题。例如,不同的包可能都使用 “sendType” 作为键来存储不同的数据,这样就会导致数据覆盖或者混乱。
而自定义一个空结构体类型 sendTypeKey 作为键,由于每个自定义类型在 Go 中都是唯一的,所以可以确保键的唯一性,避免了键冲突的问题。
类型安全
使用自定义类型作为键,在获取值时可以进行类型断言,确保获取到的数据类型是正确的
建议写法
type sendType string
func (m sendType) String() string {
return string(m)
}
const (
normalSend sendType = "normal"
batchSend sendType = "batch"
asyncSend sendType = "async"
)
type sendTypeKey struct{}
func newContextWithSendType(ctx context.Context, t sendType) context.Context {
return context.WithValue(ctx, sendTypeKey{}, t)
}
func sendTypeFromContext(ctx context.Context) (sendType, bool) {
t, ok := ctx.Value(sendTypeKey{}).(sendType)
return t, ok
}