-
Notifications
You must be signed in to change notification settings - Fork 0
/
consumer.go
88 lines (78 loc) · 2.43 KB
/
consumer.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
package fun
// Consumer represents an operation that accepts a single input argument or returns an error.
type Consumer func(v interface{}) error
// AndThen returns a composed Consumer that performs, in sequence, this operation followed by the after operation.
// If performing this operation returns an error, the after operation will not be performed.
// If after is nil, it returns original consumer.
func (c Consumer) AndThen(after Consumer) Consumer {
if after != nil {
return func(v interface{}) error {
err := c(v)
if err != nil {
return err
}
return after(v)
}
}
return c
}
// SilentConsumer represents an operation that accepts a single input argument without returning an error.
type SilentConsumer func(v interface{})
// ToSilentConsumer transforms Consumer into SilentConsumer
func (c Consumer) ToSilentConsumer() SilentConsumer {
return func(v interface{}) {
_ = c(v)
}
}
// AndThen returns a composed SilentConsumer that performs, in sequence, this operation followed by the after operation.
// If after is nil, it returns original consumer.
func (sc SilentConsumer) AndThen(after SilentConsumer) SilentConsumer {
if after != nil {
return func(v interface{}) {
sc(v)
after(v)
}
}
return sc
}
// MustConsumer represents an operation that accepts a single input argument without returning an error.
// In case of an error it should panic with error value.
type MustConsumer func(v interface{})
// ToMustConsumer transforms Consumer into MustConsumer
func (c Consumer) ToMustConsumer() MustConsumer {
return func(v interface{}) {
err := c(v)
if err != nil {
panic(err)
}
}
}
// AndThen returns a composed MustConsumer that performs, in sequence, this operation followed by the after operation.
// If performing this operation returns an error, the after operation will not be performed.
// If after is nil, it returns original consumer.
func (mc MustConsumer) AndThen(after MustConsumer) MustConsumer {
if after != nil {
return func(v interface{}) {
mc(v)
after(v)
}
}
return mc
}
// ToConsumer transforms MustConsumer into Consumer
func (mc MustConsumer) ToConsumer() Consumer {
return func(v interface{}) (err error) {
defer func() {
if r := recover(); r != nil {
err = r.(error)
}
}()
mc(v)
return
}
}
// ToSilentConsumer transforms MustConsumer into SilentConsumer
func (mc MustConsumer) ToSilentConsumer() SilentConsumer {
c := mc.ToConsumer()
return c.ToSilentConsumer()
}