From 0ebc5850cc20b62dcaa0d096be3d204cdeb91d70 Mon Sep 17 00:00:00 2001 From: Denys Kashkovskyi Date: Thu, 14 Apr 2022 09:56:32 +0000 Subject: [PATCH] Ping test --- core/printer.go | 5 ++--- core/tester.go | 34 ++++++++++++++++------------------ 2 files changed, 18 insertions(+), 21 deletions(-) diff --git a/core/printer.go b/core/printer.go index d802d90..db33167 100644 --- a/core/printer.go +++ b/core/printer.go @@ -4,7 +4,6 @@ import ( "os" "os/exec" "runtime" - "strconv" "sync" "github.com/jedib0t/go-pretty/v6/table" @@ -31,7 +30,7 @@ func NewPrinter() Printer { t := table.NewWriter() t.SetStyle(table.StyleColoredBright) t.SetOutputMirror(os.Stdout) - t.AppendHeader(table.Row{"Address", "Connection", "Status"}) + t.AppendHeader(table.Row{"Address", "Ping"}) return Printer{clearFns: clear, t: t} } @@ -42,7 +41,7 @@ func (p *Printer) ToTable(results *sync.Map) { results.Range(func(k any, r interface{}) bool { testResult, ok := r.(TestResult) if ok { - p.t.AppendRow(table.Row{k, strconv.FormatInt(testResult.duration.Milliseconds(), 10) + "ms", testResult.status}) + p.t.AppendRow(table.Row{k, testResult.ping}) } return true }) diff --git a/core/tester.go b/core/tester.go index 09c581b..8e77be7 100644 --- a/core/tester.go +++ b/core/tester.go @@ -3,15 +3,13 @@ package core import ( "fmt" "net/url" - "regexp" "time" ) type TestResult struct { - Id string - url url.URL - status string - duration time.Duration + Id string + url url.URL + ping string } type Tester struct { @@ -31,28 +29,28 @@ func NewTester(config *WatchConfig, out chan TestResult, quit chan bool) Tester } func (t *Tester) Test(url *url.URL) { - tp := NewTransport(t.requestTimeout) - for { select { case <-t.quit: return default: - _, err := tp.Dial(url.Scheme, url.Host) - - if err != nil { - t.out <- TestResult{Id: url.Host, url: *url, status: formatError(err, url), duration: tp.ConnDuration()} - return - } - - t.out <- TestResult{Id: url.Host, url: *url, status: "OK", duration: tp.Duration()} + pass := t.ping(url) + t.out <- TestResult{Id: url.Host, url: *url, ping: fmt.Sprintf("%d/10", pass)} time.Sleep(t.testInterval) } } } -func formatError(err error, url *url.URL) string { - m := regexp.MustCompile(fmt.Sprintf(`(net/http: )| \(.*\)|(dial .* %s: )`, url.Host)) - return m.ReplaceAllString(err.Error(), "") +func (t *Tester) ping(url *url.URL) int { + tp := NewTransport(t.requestTimeout) + pass := 0 + for i := 0; i < 10; i++ { + _, err := tp.Dial(url.Scheme, url.Host) + if err == nil { + pass++ + } + } + + return pass }