-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathoptions.go
More file actions
73 lines (65 loc) · 1.91 KB
/
options.go
File metadata and controls
73 lines (65 loc) · 1.91 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
package conc
import (
"context"
"sync"
"time"
)
// BlockOption define an option function applied to a nursery block.
type BlockOption func(cfg *nursery)
// WithContext returns a nursery block option that replaces nursery context with
// the given one.
func WithContext(ctx context.Context) BlockOption {
return func(n *nursery) {
n.Context, n.cancel = context.WithCancel(ctx)
}
}
// WithTimeout returns a nursery block option that wraps nursery context with
// a new one that timeout after the given duration.
func WithTimeout(timeout time.Duration) BlockOption {
return func(n *nursery) {
ctx := n.Context
if ctx == nil {
ctx = context.Background()
}
n.Context, n.cancel = context.WithTimeout(ctx, timeout)
}
}
// WithDeadline returns a nursery block option that wraps nursery context with
// a new one that will be canceled at `d`.
func WithDeadline(d time.Time) BlockOption {
return func(n *nursery) {
ctx := n.Context
if ctx == nil {
ctx = context.Background()
}
n.Context, n.cancel = context.WithDeadline(ctx, d)
}
}
// WithErrorHandler returns a nursery block option that adds an error handler to
// the block. Provided error handler is executed in the goroutine that returned
// the error.
func WithErrorHandler(handler func(error)) BlockOption {
return func(n *nursery) {
n.onError = handler
}
}
// WithCollectErrors returns a nursery block option that sets error handler to
// collect goroutine errors into provided error slice. Provided error slice must
// not be read and write until end of block.
func WithCollectErrors(errors *[]error) BlockOption {
mu := &sync.Mutex{}
return func(n *nursery) {
n.onError = func(err error) {
mu.Lock()
*errors = append(*errors, err)
mu.Unlock()
}
}
}
// WithIgnoreErrors returns a nursery block option that sets error handler to a
// noop function.
func WithIgnoreErrors() BlockOption {
return func(n *nursery) {
n.onError = func(err error) {}
}
}