2
2
package main
3
3
4
4
import (
5
+ "context"
5
6
"flag"
7
+ "io"
8
+ "net"
9
+ "net/http"
6
10
"os"
7
11
"time"
8
12
15
19
host = flag .String ("host" , "/ip4/127.0.0.1/tcp/5001" , "the multiaddr host to dial on" )
16
20
tries = flag .Int ("tries" , 10 , "how many tries to make before failing" )
17
21
timeout = flag .Duration ("tout" , time .Second , "how long to wait between attempts" )
22
+ httpURL = flag .String ("http-url" , "" , "HTTP URL to fetch" )
23
+ httpOut = flag .Bool ("http-out" , false , "Print the HTTP response body to stdout" )
18
24
verbose = flag .Bool ("v" , false , "verbose logging" )
19
25
)
20
26
@@ -37,18 +43,76 @@ func main() {
37
43
start := time .Now ()
38
44
log .Debugf ("starting at %s, tries: %d, timeout: %s, addr: %s" , start , * tries , * timeout , addr )
39
45
40
- for * tries > 0 {
46
+ connTries := * tries
47
+ for connTries > 0 {
41
48
c , err := manet .Dial (addr )
42
49
if err == nil {
43
50
log .Debugf ("ok - endpoint reachable with %d tries remaining, took %s" , * tries , time .Since (start ))
44
51
c .Close ()
45
- os . Exit ( 0 )
52
+ break
46
53
}
47
54
log .Debug ("connect failed: " , err )
48
55
time .Sleep (* timeout )
49
- * tries --
56
+ connTries --
50
57
}
51
58
52
- log .Error ("failed." )
59
+ if err != nil {
60
+ goto Fail
61
+ }
62
+
63
+ if * httpURL != "" {
64
+ dialer := & connDialer {addr : addr }
65
+ httpClient := http.Client {Transport : & http.Transport {
66
+ DialContext : dialer .DialContext ,
67
+ }}
68
+ reqTries := * tries
69
+ for reqTries > 0 {
70
+ try := (* tries - reqTries ) + 1
71
+ log .Debugf ("trying HTTP req %d: '%s'" , try , * httpURL )
72
+ if tryHTTPGet (& httpClient , * httpURL ) {
73
+ log .Debugf ("HTTP req %d to '%s' succeeded" , try , * httpURL )
74
+ goto Success
75
+ }
76
+ log .Debugf ("HTTP req %d to '%s' failed" , try , * httpURL )
77
+ time .Sleep (* timeout )
78
+ reqTries --
79
+ }
80
+ goto Fail
81
+ }
82
+
83
+ Success:
84
+ os .Exit (0 )
85
+
86
+ Fail:
87
+ log .Error ("failed" )
53
88
os .Exit (1 )
54
89
}
90
+
91
+ func tryHTTPGet (client * http.Client , url string ) bool {
92
+ resp , err := client .Get (* httpURL )
93
+ if resp != nil && resp .Body != nil {
94
+ defer resp .Body .Close ()
95
+ }
96
+ if err != nil {
97
+ return false
98
+ }
99
+ if resp .StatusCode != http .StatusOK {
100
+ return false
101
+ }
102
+ if * httpOut {
103
+ _ , err := io .Copy (os .Stdout , resp .Body )
104
+ if err != nil {
105
+ panic (err )
106
+ }
107
+ }
108
+
109
+ return true
110
+ }
111
+
112
+ type connDialer struct {
113
+ addr ma.Multiaddr
114
+ }
115
+
116
+ func (d connDialer ) DialContext (ctx context.Context , network , addr string ) (net.Conn , error ) {
117
+ return (& manet.Dialer {}).DialContext (ctx , d .addr )
118
+ }
0 commit comments