-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathoption_options.go
70 lines (56 loc) · 1.37 KB
/
option_options.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
package log
import "fmt"
type options []Option
func (o *options) append(opt ...Option) {
*o = append(*o, opt...)
}
func (o options) applySyslog(l *syslogLogger) error {
for _, opt := range o {
if err := opt.applySyslog(l); err != nil {
return err
}
}
return nil
}
func (o options) applyStdLog(l *stdLogger) error {
for _, opt := range o {
if err := opt.applyStdLog(l); err != nil {
return err
}
}
return nil
}
type OptionLoader func() (Option, error)
// Options combine multiple options into one composite option. It takes a list of Option or OptionLoader; the latter
// makes it possible to load options dynamically from environment, config files, etc
func Options(opt ...interface{}) (Option, error) {
opts := options{}
for _, o := range opt {
switch o := o.(type) {
case Option:
opts.append(o)
case OptionLoader:
lo, err := o()
if err != nil {
return nil, err
}
opts.append(lo)
case func() Option:
opts.append(o())
case func(bool) Option:
opts.append(o(true))
default:
return nil, ErrUnknownOption
}
}
return opts, nil
}
// OptionsMust checks for errors from dynamic OptionLoader combined through Options.
// It panics if err is not nil otherwise returns o.
func OptionsMust(o Option, err error) Option {
if err != nil {
panic(fmt.Errorf("failed to load options; error:%w", err))
}
return o
}
var _ Option = options{}