/
cli.go
90 lines (68 loc) · 1.45 KB
/
cli.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
85
86
87
88
89
90
package main
import (
"fmt"
"math"
"os"
"os/exec"
"strings"
"time"
)
type Result struct {
when time.Time
value bool
}
func main() {
if len(os.Args) != 2 {
fmt.Println("Please pass in the host to ping")
os.Exit(1)
}
host := os.Args[1]
channel := make(chan Result)
go pinger(channel, host)
go reporter(channel)
// sleep forever
select {}
}
func pinger(reporter chan Result, host string) {
// every second
for now := range time.Tick(1 * time.Second) {
// run the ping command
err := exec.Command("ping", "-W", "1", "-c", "1", host).Run()
// report the result
reporter <- Result{when: now, value: err == nil}
}
}
func reporter(source chan Result) {
var good int
var seconds int
var was time.Time = time.Now()
for {
result := <-source
if result.value {
good += 1
}
seconds += 1
if seconds == 1 {
fmt.Print(result.when.Format("15:04"), " |")
}
if result.value {
fmt.Print("#")
} else {
fmt.Print(".")
}
if seconds >= 60 {
summarize(good)
seconds = 0
good = 0
if was.Day() != result.when.Day() {
fmt.Println(result.when.Format("Mon 2, 2006"))
}
was = result.when
}
}
}
func summarize(good int) {
last_10 := math.Max(0, float64(good-50))
first_50 := (math.Min(0, float64(good-50)) + 50) / 10
fmt.Printf("|%s%s%s%s| %d\n", strings.Repeat("#", int(first_50)), strings.Repeat(".", 5-int(first_50)), strings.Repeat("%", int(last_10)), strings.Repeat(".", 10-int(last_10)), good)
}