-
Notifications
You must be signed in to change notification settings - Fork 0
/
utils.go
80 lines (66 loc) · 1.24 KB
/
utils.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
package main
import (
"context"
"errors"
"fmt"
"io"
"sync"
"github.com/hashicorp/go-multierror"
)
var ErrChannelClosed = fmt.Errorf("channel closed")
func chanSend[T any](ctx context.Context, c chan<- T, t T) (err error) {
defer func() {
if r := recover(); r != nil {
err = fmt.Errorf("recovered from panic: %+v", r)
}
}()
select {
case <-ctx.Done():
return ctx.Err()
case c <- t:
return
}
}
func chanRecv[T any](ctx context.Context, c <-chan T) (t T, err error) {
select {
case <-ctx.Done():
return t, ctx.Err()
case t, ok := <-c:
if !ok {
err = ErrChannelClosed
}
return t, err
}
}
func chanClose[T any](c chan T) (err error) {
defer func() {
if r := recover(); r != nil {
err = fmt.Errorf("recovered from panic: %+v", r)
}
}()
close(c)
return
}
func relay(a io.ReadWriteCloser, b io.ReadWriteCloser) (err error) {
var errA, errB error
wg := sync.WaitGroup{}
wg.Add(2)
go func() {
defer wg.Done()
defer b.Close()
_, errA = io.Copy(b, a)
}()
go func() {
defer wg.Done()
defer a.Close()
_, errB = io.Copy(a, b)
}()
wg.Wait()
switch {
default:
return multierror.Append(errA, errB)
case errA == nil || errB == nil:
case errors.Is(io.EOF, errA) || errors.Is(io.EOF, errB):
}
return
}