-
Notifications
You must be signed in to change notification settings - Fork 4
/
portchecker.go
84 lines (74 loc) · 2.34 KB
/
portchecker.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
81
82
83
84
package main
import (
"flag"
"fmt"
"github.com/hackmdio/portchecker/internal"
"io/ioutil"
"log"
"net"
"os"
"strings"
"time"
)
var (
conStr string
conStrFromEnv string
conStrFromFile string
)
func init() {
log.SetFlags(log.LstdFlags | log.Lshortfile)
flag.IntVar(&internal.DefaultRetryOptions.Attempt, "attempt", 5, "retry Attempt")
flag.Int64Var(&internal.DefaultRetryOptions.WaitTime, "wait", 3, "if connecting fail, wait how many second to retry")
flag.StringVar(&conStr, "constr", "", "try to connect")
flag.StringVar(&conStrFromEnv, "env", "", "environment with connection string")
flag.StringVar(&conStrFromFile, "file", "", "file path that contains connection string")
}
func main() {
flag.Parse()
// conStr or conStrFromEnv should only set one
if (conStr == "") && (conStrFromEnv == "") && (conStrFromFile == "") {
log.Fatalln("Error: must specific one type of conStr")
}
netPort := getNetPort()
if netPort == nil {
log.Fatalln("Error: cannot parsed connection string.")
}
attemptTime := internal.DefaultRetryOptions.Attempt
waitTime := internal.DefaultRetryOptions.WaitTime
fmt.Printf("Info: try to connect to %s://%s in port %s\n", netPort.Protocol, netPort.Address, netPort.Port)
for i := 0; i < attemptTime; i++ {
c, err := net.Dial(netPort.Protocol, netPort.GetNetworkAddress())
if err != nil {
log.Printf("%v\n wait %d seconds retry", err, waitTime)
time.Sleep(time.Duration(waitTime) * time.Second)
continue
}
_ = c.Close()
log.Printf("dial %s %s: connect: connection success\n", netPort.Protocol, netPort.GetNetworkAddress())
os.Exit(0)
}
log.Fatalf("Exceeded maximum retry attempts (%d), connot connect to %s\n", attemptTime, netPort.GetNetworkAddress())
}
func getNetPort() *internal.NetPort {
if conStr != "" {
return internal.ParseNetworkStringToNetPort(conStr)
}
if conStrFromEnv != "" {
envValue := os.Getenv(conStrFromEnv)
if envValue == "" {
fmt.Printf("Error: value of env: %s is empty!", conStrFromEnv)
os.Exit(1)
}
return internal.ParseNetworkStringToNetPort(envValue)
}
if conStrFromFile != "" {
contents, err := ioutil.ReadFile(conStrFromFile)
if err != nil {
fmt.Printf("Error: can't read file %s", conStrFromFile)
os.Exit(1)
}
trimConnStr := strings.TrimSpace(string(contents))
return internal.ParseNetworkStringToNetPort(trimConnStr)
}
return nil
}