Skip to content

Commit

Permalink
Ping test
Browse files Browse the repository at this point in the history
  • Loading branch information
Kashkovsky committed Apr 14, 2022
1 parent 965076e commit 0ebc585
Show file tree
Hide file tree
Showing 2 changed files with 18 additions and 21 deletions.
5 changes: 2 additions & 3 deletions core/printer.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,6 @@ import (
"os"
"os/exec"
"runtime"
"strconv"
"sync"

"github.com/jedib0t/go-pretty/v6/table"
Expand All @@ -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}
}
Expand All @@ -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
})
Expand Down
34 changes: 16 additions & 18 deletions core/tester.go
Original file line number Diff line number Diff line change
Expand Up @@ -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 {
Expand All @@ -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
}

0 comments on commit 0ebc585

Please sign in to comment.