Eclectic Media Git pingstats-go / ae7fe43
Initial commit Ariana Giroux 11 months ago
1 changed file(s) with 80 addition(s) and 0 deletion(s). Raw diff Collapse all Expand all
0 package main
1
2 // import "errors"
3 import "fmt"
4 import "github.com/guptarohit/asciigraph"
5 import terminal "github.com/wayneashleyberry/terminal-dimensions"
6 import "os/exec"
7 import "strconv"
8 import "strings"
9 import "time"
10
11 // define a pingstats clone in go
12 func main() {
13 var returnTimes []float64
14
15 for i := 0; i < 500; i++ {
16 width, height := termsize()
17 returnTimes = append(returnTimes, get_return_time("google.ca"))
18
19 graph := asciigraph.Plot(returnTimes,
20 asciigraph.Width(int(width)-10),
21 asciigraph.Height(int(height)-2))
22
23 fmt.Println(graph)
24 time.Sleep(100 * time.Millisecond)
25 clear()
26 }
27 }
28
29 func get_return_time(host string) float64 { // retrieve return time from ping as float64
30 pingCmd := exec.Command("ping", "-c 1", host) // Run ping command
31 pingOut, err := pingCmd.Output() // Obtain command output
32
33 var returnTime float64
34
35 if err != nil {
36 panic(err)
37 }
38
39 for _, line := range strings.Split(string(pingOut), "\n") { // split output by line
40 if strings.Contains(string(line), "time=") { // line has time value on it
41 timeIndex := strings.Index(line, "time") // get index of time data
42 subIndex := strings.Index(string(line[timeIndex:]), "=") + 1 // Get index of equals sign, plus one
43 endIndex := strings.Index(string(line[timeIndex:]), " ") // get index of trailing characters
44
45 rTime, err := strconv.ParseFloat(
46 string(line)[timeIndex:][subIndex:endIndex], // return relevant data as sub string
47 64,
48 )
49
50 if err != nil {
51 panic(err)
52 } else {
53 returnTime = rTime // if no errors, set returnTime to data
54 }
55 }
56 }
57
58 return returnTime
59 }
60
61 func termsize() (int, int) { // return size of terminal
62 // obtain width
63 width, err := terminal.Width()
64 if err != nil {
65 panic(err)
66 }
67
68 // obtain height
69 height, err := terminal.Height()
70 if err != nil {
71 panic(err)
72 }
73
74 return int(width), int(height)
75 }
76
77 func clear() { // clear terminal
78 exec.Command("clear")
79 }