func.go 1.0 KB

1234567891011121314151617181920212223242526272829303132333435
  1. package contextkey
  2. import (
  3. "context"
  4. )
  5. // Key 泛型键对象,封装特定类型的上下文存取
  6. type CtxKey[T any] struct {
  7. key any // 实际存储的唯一键(通过空结构体保证类型唯一)
  8. }
  9. // NewKey 创建管理特定类型值的键对象(每个调用生成唯一键)
  10. func NewCtxKey[T any]() CtxKey[T] {
  11. type uniqueKey struct{} // 闭包内部类型确保唯一性
  12. return CtxKey[T]{key: uniqueKey{}}
  13. }
  14. // WithValue 将值存入context,返回新context
  15. func (k CtxKey[T]) WithValue(ctx context.Context, value T) context.Context {
  16. //fmt.Printf("WithValue=====>key:%v|addr:%p\n", k.key, &k.key)
  17. return context.WithValue(ctx, k.key, value)
  18. }
  19. // GetValue 从context中提取值(带类型安全校验)
  20. func (k CtxKey[T]) GetValue(ctx context.Context) (T, bool) {
  21. //fmt.Printf("GetValue#1=====>key:%v|addr:%p\n", k.key, &k.key)
  22. v := ctx.Value(k.key)
  23. if v == nil {
  24. var zero T
  25. return zero, false
  26. }
  27. //fmt.Printf("GetValue#2=====>key:%v|addr:%p\n", k.key, &k.key)
  28. t, ok := v.(T)
  29. return t, ok
  30. }