-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathstartstopper_example_test.go
More file actions
84 lines (64 loc) · 1.24 KB
/
startstopper_example_test.go
File metadata and controls
84 lines (64 loc) · 1.24 KB
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
package startstopper_test
import (
"fmt"
"github.com/Darigaaz/startstopper"
)
type Srv struct {
startstopper.StartStopper
C chan int
}
func NewSrv() *Srv {
service := &Srv{
C: make(chan int),
}
return service
}
func (srv *Srv) DoStuff(n int) {
srv.C <- n
}
func (srv *Srv) Start(signal chan error) {
var lastError error
closingCh, err := srv.StartStopper.Start(signal)
if err != nil {
return
}
for {
select {
// listen to closingCh in main loop
case done := <-closingCh:
lastError = srv.cleanup()
// response with error or nil when you are done cleaning up
done(lastError)
// dont forget to return
return
// other cases
case v := <-srv.C:
fmt.Println(v)
}
}
}
func (srv *Srv) Stop(errCh chan error) {
srv.StartStopper.Stop(errCh)
}
func (srv *Srv) cleanup() error {
return nil
}
func ExampleStartStopper() {
srv := NewSrv()
readyCh := make(chan error, 1)
// pass readyCh or nil if you dont want to be notified on 'started'
go srv.Start(readyCh)
<-readyCh
srv.DoStuff(1)
srv.DoStuff(2)
srv.DoStuff(3)
stoppedCh := make(chan error, 1)
// pass stoppedCh or nil if you dont want to be notified on 'stopped'
srv.Stop(stoppedCh)
fmt.Println(<-stoppedCh)
// Output:
// 1
// 2
// 3
// <nil>
}