-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathexample_test.go
112 lines (92 loc) · 1.89 KB
/
example_test.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
108
109
110
111
112
package regwatch
import (
"fmt"
"sync"
"os"
"os/signal"
"context"
"runtime"
"testing"
"time"
)
const keyPath = `SOFTWARE\Foo\Bar`
func TestExample(t *testing.T) {
runtime.LockOSThread()
runtime.GOMAXPROCS(runtime.NumCPU())
ctx, cancelFn := cancelHandler()
wg := &sync.WaitGroup{}
wg.Add(2)
w, err := NewWatcher(HKeyLocalMachine, keyPath, 1000)
must(err)
go func() {
<-time.After(5 * time.Second)
fmt.Printf("INFO:\tstopping...\n")
cancelFn()
os.Exit(1)
}()
updates := make(chan string)
go func() {
fmt.Printf("INFO:\tconsumer: start...\n")
for {
kp, ok := <-updates
if !ok {
fmt.Printf("INFO:\tconsumer: shutdown...\n")
return
}
fmt.Printf("INFO:\t consumer: Received update msg - '%s'\n", kp)
}
}()
go func() {
fmt.Printf("INFO:\tLooking for changes in '%s'...\n", keyPath)
defer func() {
if err := w.Destroy(); err != nil {
fmt.Printf("ERROR:\tWatcher.Destroy - %s\n", err)
}
close(updates)
wg.Done();
}()
for {
select {
case <-ctx.Done():
fmt.Printf("INFO:\tGot shutdown signal...\n")
return
default:
}
changed, err := w.Await()
if err != nil {
fmt.Printf("ERROR:\tWatcher.Await - %s\n", err)
return
}
if !changed {
continue
}
fmt.Printf("INFO:\t'%s' changed\n", keyPath)
updates <- keyPath
}
}()
fmt.Println("Waiting...")
wg.Wait()
fmt.Println("Goodbye")
}
// cancelHandler returns cancellation context and function for graceful shutdown
func cancelHandler() (context.Context, context.CancelFunc) {
ctx, cancelFn := context.WithCancel(context.Background())
signals := make(chan os.Signal, 1)
signal.Notify(signals, os.Interrupt)
go func() {
<-signals
cancelFn()
signal.Stop(signals)
}()
return ctx, cancelFn
}
func must(err error) {
if err != nil {
panic(err)
}
}
func try(err error) {
if err != nil {
_, _ = fmt.Fprintf(os.Stderr, "ERR: %s\n", err)
}
}