github.com/jmigpin/editor@v1.6.0/util/ctxutil/ctx.go (about)

     1  package ctxutil
     2  
     3  // This is a reference implementation. In many cases it works best to just copy this code and keep adding methods instead of embedding.
     4  
     5  type Ctx struct {
     6  	Parent *Ctx
     7  	// name/value (short names to avoid usage, still exporting it)
     8  	N string
     9  	V interface{}
    10  }
    11  
    12  func (ctx *Ctx) WithValue(name string, value interface{}) *Ctx {
    13  	return &Ctx{ctx, name, value}
    14  }
    15  
    16  func (ctx *Ctx) Value(name string) (interface{}, *Ctx) {
    17  	for c := ctx; c != nil; c = c.Parent {
    18  		if c.N == name {
    19  			return c.V, c
    20  		}
    21  	}
    22  	return nil, nil
    23  }
    24  
    25  //----------
    26  
    27  func (ctx *Ctx) ValueBool(name string) bool {
    28  	v, _ := ctx.Value(name)
    29  	if v == nil {
    30  		return false
    31  	}
    32  	return v.(bool)
    33  }
    34  
    35  func (ctx *Ctx) ValueInt(name string) int {
    36  	v, _ := ctx.Value(name)
    37  	if v == nil {
    38  		return 0
    39  	}
    40  	return v.(int)
    41  }