-
-
Notifications
You must be signed in to change notification settings - Fork 1
/
wait.go
48 lines (40 loc) · 896 Bytes
/
wait.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
package waitforhttp
import (
"fmt"
"net"
"net/http"
"time"
"github.com/avast/retry-go"
)
// Wait for the supplied server to start listening and return nil, or return error if timeout is reached
func Wait(server *http.Server, timeout time.Duration) error {
delay := time.Millisecond * 50
var attempts uint
if timeout < delay {
attempts = 1
} else {
attempts = uint((timeout / delay) + 1)
}
if server == nil {
return fmt.Errorf("server cannot be nil")
}
if err := retry.Do(
func() error {
conn, err := net.Dial("tcp", server.Addr)
if err != nil {
return err
}
_ = conn.Close()
return nil
},
retry.Attempts(attempts),
retry.DelayType(
func(n uint, err error, config *retry.Config) time.Duration {
return delay
},
),
); err != nil {
return fmt.Errorf("timed out waiting for server to be ready at %s", server.Addr)
}
return nil
}