-
Notifications
You must be signed in to change notification settings - Fork 53
/
servers.go
76 lines (72 loc) · 1.73 KB
/
servers.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
package util
import (
"context"
"net"
"net/http"
"reflect"
"github.com/samber/lo"
)
// ServeHandler serves a http.Handler with the given listener. If the context
// is canceled, the server will be closed.
func ServeHandler(ctx context.Context, handler http.Handler, listener net.Listener) error {
server := &http.Server{
Handler: handler,
}
errC := lo.Async(func() error {
return server.Serve(listener)
})
select {
case <-ctx.Done():
server.Close()
return ctx.Err()
case err := <-errC:
return err
}
}
// WaitAll waits for all the given channels to be closed, under the
// following rules:
// 1. The lifetime of the task represented by each channel is directly tied to
// the provided context.
// 2. If a task exits with an error before the context is canceled, the
// context should be canceled.
// 3. If a task exits successfully, the context should not be canceled and
// other tasks should continue to run.
func WaitAll(ctx context.Context, ca context.CancelFunc, channels ...<-chan error) error {
cases := []reflect.SelectCase{
{
Dir: reflect.SelectRecv,
Chan: reflect.ValueOf(ctx.Done()),
},
}
for _, ch := range channels {
cases = append(cases, reflect.SelectCase{
Dir: reflect.SelectRecv,
Chan: reflect.ValueOf(ch),
})
}
i, value, _ := reflect.Select(cases)
if i == 0 {
ca()
for _, c := range channels {
<-c
}
return ctx.Err()
}
channelIdx := i - 1
var err error
if i := value.Interface(); i != nil {
err = i.(error)
}
if err == nil {
// run again, but skip the channel which exited successfully
return WaitAll(ctx, ca, append(channels[:channelIdx], channels[channelIdx+1:]...)...)
}
ca()
for i, c := range channels {
if i == channelIdx {
continue
}
<-c
}
return err
}