2016-12-29 21:17:12 +00:00
|
|
|
package signal
|
|
|
|
|
2017-01-28 20:24:46 +00:00
|
|
|
import (
|
|
|
|
"context"
|
|
|
|
)
|
|
|
|
|
2016-12-29 21:17:12 +00:00
|
|
|
func executeAndFulfill(f func() error, done chan<- error) {
|
|
|
|
err := f()
|
|
|
|
if err != nil {
|
|
|
|
done <- err
|
|
|
|
}
|
|
|
|
close(done)
|
|
|
|
}
|
|
|
|
|
2017-02-23 18:30:37 +00:00
|
|
|
// ExecuteAsync executes a function asychrously and return its result.
|
2016-12-29 21:17:12 +00:00
|
|
|
func ExecuteAsync(f func() error) <-chan error {
|
|
|
|
done := make(chan error, 1)
|
|
|
|
go executeAndFulfill(f, done)
|
|
|
|
return done
|
|
|
|
}
|
|
|
|
|
2017-01-28 20:24:46 +00:00
|
|
|
func ErrorOrFinish1(ctx context.Context, c <-chan error) error {
|
|
|
|
select {
|
|
|
|
case <-ctx.Done():
|
|
|
|
return ctx.Err()
|
|
|
|
case err := <-c:
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
func ErrorOrFinish2(ctx context.Context, c1, c2 <-chan error) error {
|
2016-12-29 21:17:12 +00:00
|
|
|
select {
|
2017-01-28 20:24:46 +00:00
|
|
|
case <-ctx.Done():
|
|
|
|
return ctx.Err()
|
2017-04-17 17:33:22 +00:00
|
|
|
case err := <-c1:
|
|
|
|
if err != nil {
|
2016-12-29 21:17:12 +00:00
|
|
|
return err
|
|
|
|
}
|
2017-01-28 20:24:46 +00:00
|
|
|
return ErrorOrFinish1(ctx, c2)
|
2017-04-17 17:33:22 +00:00
|
|
|
case err := <-c2:
|
|
|
|
if err != nil {
|
2016-12-29 21:17:12 +00:00
|
|
|
return err
|
|
|
|
}
|
2017-01-28 20:24:46 +00:00
|
|
|
return ErrorOrFinish1(ctx, c1)
|
2016-12-29 21:17:12 +00:00
|
|
|
}
|
|
|
|
}
|