From 6c264e7a9758dcd19ff1eb34cb91c1729a94e961 Mon Sep 17 00:00:00 2001 From: Ulric Qin Date: Sun, 15 Oct 2023 13:52:30 +0800 Subject: [PATCH] add tcpx.WaitHosts --- net/tcpx/tcpx.go | 38 ++++++++++++++++++++++++++++++++++++++ 1 file changed, 38 insertions(+) create mode 100644 net/tcpx/tcpx.go diff --git a/net/tcpx/tcpx.go b/net/tcpx/tcpx.go new file mode 100644 index 0000000..2b76126 --- /dev/null +++ b/net/tcpx/tcpx.go @@ -0,0 +1,38 @@ +package tcpx + +import ( + "fmt" + "net" + "os" + "strings" + "time" +) + +func WaitHosts() { + hosts := os.Getenv("WAIT_HOSTS") + if len(hosts) == 0 { + return + } + + hosts = strings.ReplaceAll(hosts, ",", " ") + array := strings.Fields(hosts) + + for _, host := range array { + waitHost(host) + } +} + +func waitHost(host string) { + for { + fmt.Printf("[%s] Waiting for host: %s\n", time.Now(), host) + + conn, err := net.DialTimeout("tcp", host, time.Second) + if err == nil { + conn.Close() + fmt.Printf("[%s] Host is ready: %s\n", time.Now(), host) + return + } + + time.Sleep(time.Second) + } +}