-
-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathpipe_ext.go
More file actions
52 lines (42 loc) · 788 Bytes
/
pipe_ext.go
File metadata and controls
52 lines (42 loc) · 788 Bytes
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
package pipe
import "context"
func New(ctx context.Context) *State {
st := NewState(nil, nil)
st.ctx = ctx
return st
}
type Result struct {
State *State
Error error
}
func Do(parent context.Context, s *State, pipe Pipe) error {
if err := pipe(s); err != nil {
return err
}
ch := make(chan error)
go func() {
ch <- s.Run(parent)
}()
return <-ch
}
func (s *State) Run(parent context.Context) error {
var ctx context.Context
var cancel context.CancelFunc
if parent != nil {
ctx, cancel = context.WithCancel(parent)
} else {
ctx, cancel = context.WithCancel(context.Background())
}
defer cancel()
ch := make(chan error)
go func() {
ch <- s.RunTasks()
}()
select {
case err := <-ch:
return err
case <-ctx.Done():
s.Kill()
return ctx.Err()
}
}