aboutsummaryrefslogtreecommitdiff
path: root/pkg/coroutine/coroutine.go
blob: 96d149ea9851318b4ff9c0c7a0f07a1a6505eb83 (plain)
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
package coroutine

import (
	"context"
)

// WrapProcess wraps process into a go routine and make it cancelable through context
func WrapProcess[V any](ctx context.Context, fun func() (V, error)) (V, error) {
	c := make(chan V)
	e := make(chan error)
	go func() {
		defer close(c)
		defer close(e)

		v, err := fun()
		if err != nil {
			e <- err
		} else {
			c <- v
		}
	}()

	select {
	case <-ctx.Done():
		var zero V
		return zero, ctx.Err()
	case m := <-c:
		return m, nil
	case err := <-e:
		var zero V
		return zero, err
	}
}