cbded934d2829f1a268ec60c14c39af46353c3fe.svn-base 726 B

12345678910111213141516171819202122232425262728293031323334353637383940414243
  1. package main
  2. import (
  3. "context"
  4. "fmt"
  5. "sync"
  6. )
  7. type MyContext struct {
  8. ctx context.Context
  9. m sync.Map
  10. }
  11. func (m * MyContext) WithValue(parent MyContext, key, val interface{}) MyContext {
  12. //ctx := m.WithValue(parent,key,val)
  13. ctx := new(MyContext)
  14. ctx.ctx =context.WithValue(parent.ctx,key,val)
  15. m.m.Store(key,val)
  16. ctx.m = m.m
  17. return *ctx
  18. }
  19. func (m * MyContext) Value( key interface{}) interface{}{
  20. val ,_ :=m.m.Load(key)
  21. return val
  22. }
  23. func NewMyContext() MyContext{
  24. mc := MyContext{
  25. ctx : context.Background(),
  26. }
  27. return mc
  28. }
  29. func main() {
  30. mc := NewMyContext()
  31. ctx :=mc.WithValue(mc,"key1","value1")
  32. ctx1 :=mc.WithValue(ctx,"key2","value2")
  33. fmt.Println(ctx.Value("key2"),ctx1.Value("key2"))
  34. }