-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathconn.go
More file actions
78 lines (72 loc) · 1.7 KB
/
conn.go
File metadata and controls
78 lines (72 loc) · 1.7 KB
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
package netutils
import (
"fmt"
"net"
"net/url"
"time"
"github.com/jpillora/backoff"
)
// getHostnameFromString will return a hostname if a url is passed
// and attempt to add the correct ports
func getHostnameFromString(potentialHost string) (string, error) {
parsedURL, err := url.Parse(potentialHost)
if err != nil {
return potentialHost, nil
}
if parsedURL.Scheme != "" && parsedURL.Host != "" {
port := parsedURL.Port()
if port == "" {
// net requires a port
switch parsedURL.Scheme {
case "https":
port = "443"
case "http":
port = "80"
default:
return "", fmt.Errorf("host appears to be url, but could not find port for scheme")
}
}
return fmt.Sprintf("%s:%s", parsedURL.Hostname(), port), nil
}
return potentialHost, nil
}
// WaitForConnectTimeout will wait for a connection
// on a port progressively backing off
// returns false if we couldn't establish a connection by timeout
// after 10 timeouts
func WaitForConnectTimeout(host string, timeout time.Duration) bool {
connected := false
host, err := getHostnameFromString(host)
if err != nil {
return false
}
b := &backoff.Backoff{
Factor: 2,
Jitter: true,
Min: timeout / 10,
Max: timeout,
}
for {
b.Attempt()
conn, err := net.Dial("tcp", host)
if err != nil {
d := b.Duration()
if d == timeout && b.Attempt() > 10 {
return false
}
time.Sleep(d)
continue
}
connected = true
b.Reset()
_ = conn.Close()
break
}
return connected
}
// WaitForConnect on a port progressively backing off
// returns false if we couldn't establish a connection
// uses default timeout of 5 seconds
func WaitForConnect(host string) bool {
return WaitForConnectTimeout(host, time.Second*5)
}