/
ping.go
67 lines (60 loc) · 1.16 KB
/
ping.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
package main
import (
"context"
"flag"
"fmt"
"net/http"
"net/http/httputil"
"time"
"github.com/gobwas/cli"
)
type ping struct {
core *core
interval time.Duration
method string
}
func (p *ping) DefineFlags(fs *flag.FlagSet) {
fs.DurationVar(&p.interval,
"interval", time.Second,
"how frequent to ping",
)
fs.StringVar(&p.method,
"method", "HEAD",
"method to be used for ping",
)
}
func (p *ping) Synopsis() string {
return "<host>[ host...]"
}
func (p *ping) Run(ctx context.Context, args []string) error {
if len(args) == 0 {
return cli.Exitf(2, "no hosts to ping were given")
}
for {
for _, host := range args {
req, err := http.NewRequest(p.method, host, nil)
if err != nil {
return err
}
if p.core.verbose {
dump, _ := httputil.DumpRequest(req, false)
fmt.Println(string(dump))
}
res, err := http.DefaultClient.Do(req.WithContext(ctx))
if err != nil {
return err
}
if p.core.verbose {
dump, _ := httputil.DumpResponse(res, false)
fmt.Println(string(dump))
} else {
fmt.Print(".")
}
}
select {
case <-ctx.Done():
return ctx.Err()
case <-time.After(p.interval):
}
}
}