-
Notifications
You must be signed in to change notification settings - Fork 0
/
config.go
97 lines (78 loc) · 2.39 KB
/
config.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
package dominoes
import (
"context"
"io"
"os"
"syscall"
)
type configuration struct {
listeners []Listener
managed []io.Closer
signals []os.Signal
logger logger
shutdown context.CancelFunc
}
func New(options ...option) ListenCloser {
var config configuration
Options.apply(options...)(&config)
return newSignalWatcher(newListener(config), config)
}
var Options singleton
type singleton struct{}
type option func(*configuration)
func (singleton) AddOptionalListeners(value ...Listener) option {
var populated []Listener
for _, listener := range value {
if listener != nil {
populated = append(populated, listener)
}
}
return Options.AddListeners(populated...)
}
func (singleton) AddListeners(value ...Listener) option {
return func(this *configuration) { this.listeners = append(this.listeners, value...) }
}
func (singleton) AddManagedResource(value ...io.Closer) option {
return func(this *configuration) { this.managed = append(this.managed, value...) }
}
func (singleton) AddContextShutdown(value context.CancelFunc) option {
return func(this *configuration) { this.shutdown = value }
}
func (singleton) WatchTerminateSignals() option {
return Options.WatchSignals(syscall.SIGINT, syscall.SIGTERM)
}
func (singleton) WatchSignals(value ...os.Signal) option {
return func(this *configuration) { this.signals = append(this.signals, value...) }
}
func (singleton) Logger(value logger) option {
return func(this *configuration) { this.logger = value }
}
func (singleton) apply(options ...option) option {
return func(this *configuration) {
for _, item := range Options.defaults(options...) {
item(this)
}
if len(this.listeners) == 0 {
this.listeners = append(this.listeners, &nop{})
}
this.managed = append(this.managed, shutdownCloser(this.shutdown))
}
}
func (singleton) defaults(options ...option) []option {
return append([]option{
Options.Logger(&nop{}),
}, options...)
}
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
type shutdownCloser context.CancelFunc
func (this shutdownCloser) Close() error {
if this != nil {
this()
}
return nil
}
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
type nop struct{}
func (*nop) Printf(_ string, _ ...any) {}
func (*nop) Println(_ ...any) {}
func (*nop) Listen() {}