-
Notifications
You must be signed in to change notification settings - Fork 6
/
options.go
115 lines (99 loc) · 2.44 KB
/
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
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
113
114
115
package buffer
import (
"errors"
"fmt"
"time"
)
const (
invalidSize = "size cannot be zero"
invalidFlusher = "flusher cannot be nil"
invalidInterval = "interval must be greater than zero (%s)"
invalidTimeout = "timeout cannot be negative (%s)"
)
type (
// Configuration options.
Options struct {
Size uint
Flusher Flusher
FlushInterval time.Duration
PushTimeout time.Duration
FlushTimeout time.Duration
CloseTimeout time.Duration
}
// Option setter.
Option func(*Options)
)
// WithSize sets the size of the buffer.
func WithSize(size uint) Option {
return func(options *Options) {
options.Size = size
}
}
// WithFlusher sets the flusher that should be used to write out the buffer.
func WithFlusher(flusher Flusher) Option {
return func(options *Options) {
options.Flusher = flusher
}
}
// WithFlushInterval sets the interval between automatic flushes.
func WithFlushInterval(interval time.Duration) Option {
return func(options *Options) {
options.FlushInterval = interval
}
}
// WithPushTimeout sets how long a push should wait before giving up.
func WithPushTimeout(timeout time.Duration) Option {
return func(options *Options) {
options.PushTimeout = timeout
}
}
// WithFlushTimeout sets how long a manual flush should wait before giving up.
func WithFlushTimeout(timeout time.Duration) Option {
return func(options *Options) {
options.FlushTimeout = timeout
}
}
// WithCloseTimeout sets how long
func WithCloseTimeout(timeout time.Duration) Option {
return func(options *Options) {
options.CloseTimeout = timeout
}
}
func validateOptions(options *Options) error {
if options.Size == 0 {
return errors.New(invalidSize)
}
if options.Flusher == nil {
return errors.New(invalidFlusher)
}
if options.FlushInterval < 0 {
return fmt.Errorf(invalidInterval, "FlushInterval")
}
if options.PushTimeout < 0 {
return fmt.Errorf(invalidTimeout, "PushTimeout")
}
if options.FlushTimeout < 0 {
return fmt.Errorf(invalidTimeout, "FlushTimeout")
}
if options.CloseTimeout < 0 {
return fmt.Errorf(invalidTimeout, "CloseTimeout")
}
return nil
}
func resolveOptions(opts ...Option) *Options {
options := &Options{
Size: 0,
Flusher: nil,
FlushInterval: 0,
PushTimeout: time.Second,
FlushTimeout: time.Second,
CloseTimeout: time.Second,
}
for _, opt := range opts {
opt(options)
}
if err := validateOptions(options); err != nil {
panic(err)
}
return options
}