-
Notifications
You must be signed in to change notification settings - Fork 3
/
example.go
107 lines (87 loc) · 1.67 KB
/
example.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
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
package example
import (
"context"
"fmt"
lifecycle "github.com/boz/go-lifecycle"
)
var (
ErrNotRunning = fmt.Errorf("not running")
)
type Cache interface {
Put(string, string) error
Get(string) (string, error)
Shutdown(error)
ShutdownAsync(error)
Done() <-chan struct{}
Error() error
}
type cache struct {
lc lifecycle.Lifecycle
putch chan putreq
getch chan getreq
items map[string]string
}
type putreq struct {
key string
value string
}
type getreq struct {
key string
valch chan<- string
}
func NewCache(ctx context.Context) Cache {
c := &cache{
lc: lifecycle.New(),
putch: make(chan putreq),
getch: make(chan getreq),
items: make(map[string]string),
}
go c.lc.WatchContext(ctx)
go c.run()
return c
}
func (c *cache) run() {
defer c.lc.ShutdownCompleted()
loop:
for {
select {
case err := <-c.lc.ShutdownRequest():
c.lc.ShutdownInitiated(err)
break loop
case req := <-c.putch:
c.items[req.key] = req.value
case req := <-c.getch:
req.valch <- c.items[req.key]
}
}
// shutdown, wait for child resources
}
func (c *cache) Put(key, value string) error {
select {
case c.putch <- putreq{key, value}:
return nil
case <-c.lc.ShuttingDown():
return ErrNotRunning
}
}
func (c *cache) Get(key string) (string, error) {
valch := make(chan string)
select {
case c.getch <- getreq{key, valch}:
return <-valch, nil
case <-c.lc.ShuttingDown():
return "", ErrNotRunning
}
}
func (c *cache) Shutdown(err error) {
c.lc.Shutdown(err)
}
func (c *cache) ShutdownAsync(err error) {
c.lc.ShutdownAsync(err)
}
func (c *cache) Done() <-chan struct{} {
return c.lc.Done()
}
func (c *cache) Error() error {
return c.lc.Error()
}