2
0

context.go 1.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061
  1. package worker
  2. // Context object aims to store runtime configurations
  3. import "errors"
  4. // A Context object is a layered key-value storage
  5. // when enters a context, the changes to the storage would be stored
  6. // in a new layer and when exits, the top layer poped and the storage
  7. // returned to the state before entering this context
  8. type Context struct {
  9. parent *Context
  10. store map[string]interface{}
  11. }
  12. // NewContext returns a new context object
  13. func NewContext() *Context {
  14. return &Context{
  15. parent: nil,
  16. store: make(map[string]interface{}),
  17. }
  18. }
  19. // Enter generates a new layer of context
  20. func (ctx *Context) Enter() *Context {
  21. return &Context{
  22. parent: ctx,
  23. store: make(map[string]interface{}),
  24. }
  25. }
  26. // Exit return the upper layer of context
  27. func (ctx *Context) Exit() (*Context, error) {
  28. if ctx.parent == nil {
  29. return nil, errors.New("Cannot exit the bottom layer context")
  30. }
  31. return ctx.parent, nil
  32. }
  33. // Get returns the value corresponding to key, if it's
  34. // not found in the current layer, return the lower layer
  35. // context's value
  36. func (ctx *Context) Get(key string) (interface{}, bool) {
  37. if ctx.parent == nil {
  38. if value, ok := ctx.store[key]; ok {
  39. return value, true
  40. }
  41. return nil, false
  42. }
  43. if value, ok := ctx.store[key]; ok {
  44. return value, true
  45. }
  46. return ctx.parent.Get(key)
  47. }
  48. // Set sets the value to the key at current layer
  49. func (ctx *Context) Set(key string, value interface{}) {
  50. ctx.store[key] = value
  51. }