-
Notifications
You must be signed in to change notification settings - Fork 0
/
ctx.go
55 lines (49 loc) · 928 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
42
43
44
45
46
47
48
49
50
51
52
53
54
55
package ctx
// Ctx is a context that can store key-value pairs.
type Ctx struct {
*Ctx
key string
val any
}
// Set sets a key-value pair in the context.
func (c *Ctx) Set(key string, val any) {
if key == "" {
c.key = key
c.val = val
} else if c.Ctx == nil {
c.Ctx = &Ctx{key: key, val: val}
} else {
c.Ctx.Set(key, val)
}
}
func (c *Ctx) unset(key string) {
if c.Ctx != nil {
if c.Ctx.key == key {
c.Ctx = c.Ctx.Ctx
return
}
c.Ctx.Unset(key)
}
}
// Unset removes a key-value pair from the context.
func (c *Ctx) Unset(key string) {
if c.key == key {
c.key = ""
} else if c.Ctx != nil {
c.unset(key)
}
}
// Get returns a value by its key.
func (c *Ctx) Get(key string) (bool, any) {
if c.key == key {
return true, c.val
}
if c.Ctx == nil {
return false, nil
}
return c.Ctx.Get(key)
}
// Clear removes all key-value pairs from the context.
func (c *Ctx) Clear() {
c.Ctx = nil
}