forked from syafdia/go-exercise
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathpipeline.go
60 lines (46 loc) · 1.01 KB
/
pipeline.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
package pipeline
type Executor func(interface{}) (interface{}, error)
type Pipeline interface {
Pipe(executor Executor) Pipeline
Merge() <-chan interface{}
}
type pipeline struct {
dataC chan interface{}
errC chan error
executors []Executor
}
func New(f func(chan interface{})) Pipeline {
inC := make(chan interface{})
go f(inC)
return &pipeline{
dataC: inC,
errC: make(chan error),
executors: []Executor{},
}
}
func (p *pipeline) Pipe(executor Executor) Pipeline {
p.executors = append(p.executors, executor)
return p
}
func (p *pipeline) Merge() <-chan interface{} {
for i := 0; i < len(p.executors); i++ {
p.dataC, p.errC = run(p.dataC, p.executors[i])
}
return p.dataC
}
func run(inC <-chan interface{}, f Executor) (chan interface{}, chan error) {
outC := make(chan interface{})
errC := make(chan error)
go func() {
defer close(outC)
for v := range inC {
res, err := f(v)
if err != nil {
errC <- err
continue
}
outC <- res
}
}()
return outC, errC
}