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