From 08245c1ba97205a1c2800e2acb537a90f4550caa Mon Sep 17 00:00:00 2001 From: bel Date: Mon, 8 Jun 2026 13:39:52 -0600 Subject: [PATCH] ojson --- main.go | 39 ++++++++++++++++++++++++++++++--------- 1 file changed, 30 insertions(+), 9 deletions(-) diff --git a/main.go b/main.go index 1d5606d..c28b536 100644 --- a/main.go +++ b/main.go @@ -1,6 +1,7 @@ package main import ( + "encoding/json" "flag" "fmt" "os" @@ -19,6 +20,7 @@ func run() error { fs := flag.NewFlagSet(os.Args[0], flag.ContinueOnError) domain := fs.String("d", "www.google.com", "address to ping") c := fs.Int("c", 0, "limit pings") + o := fs.String("o", "csv", "output format (csv, json)") if err := fs.Parse(os.Args[1:]); err != nil { return err } @@ -30,17 +32,36 @@ func run() error { pinger.Count = *c pinger.SetPrivileged(true) - fmt.Printf("ts,n,ok_pct,max,avg,stddev\n") + switch *o { + case "csv": + fmt.Printf("ts,n,ok_pct,max,avg,stddev\n") + case "json": + default: + panic(*o) + } pinger.OnRecv = func(*ping.Packet) { stat := pinger.Statistics() - fmt.Printf("%s,%d,%.0f%%,%dms,%dms,%dms\n", - time.Now().UTC().Format("2006-01-02T15:04:05Z"), - stat.PacketsRecv, - 100.0*(1.0-stat.PacketLoss), - stat.MaxRtt.Milliseconds(), - stat.AvgRtt.Milliseconds(), - stat.StdDevRtt.Milliseconds(), - ) + switch *o { + case "csv": + fmt.Printf("%s,%d,%.0f%%,%dms,%dms,%dms\n", + time.Now().UTC().Format("2006-01-02T15:04:05Z"), + stat.PacketsRecv, + 100.0*(1.0-stat.PacketLoss), + stat.MaxRtt.Milliseconds(), + stat.AvgRtt.Milliseconds(), + stat.StdDevRtt.Milliseconds(), + ) + case "json": + b, _ := json.Marshal(map[string]any{ + "ts": time.Now().UTC().Format("2006-01-02T15:04:05Z"), + "n": stat.PacketsRecv, + "ok_pct": 100.0 * (1.0 - stat.PacketLoss), + "max": stat.MaxRtt.Milliseconds(), + "avg": stat.AvgRtt.Milliseconds(), + "stddev": stat.StdDevRtt.Milliseconds(), + }) + fmt.Printf("%s\n", b) + } } if err := pinger.Run(); err != nil {