apps-durpcli/cmd/net/ping.go

56 lines
900 B
Go
Raw Permalink Normal View History

2023-02-19 13:44:18 -06:00
package net
import (
"fmt"
"net/http"
"time"
"github.com/spf13/cobra"
)
var (
urlPath string
2023-05-27 11:43:24 -05:00
client = http.Client{
2023-02-19 18:20:25 -06:00
Timeout: time.Second * 2,
2023-02-19 13:44:18 -06:00
}
)
func ping(domain string) (int, error) {
2023-02-19 18:20:25 -06:00
url := "http://" + domain
2023-02-19 13:44:18 -06:00
req, err := http.NewRequest("HEAD", url, nil)
if err != nil {
return 0, err
}
resp, err := client.Do(req)
if err != nil {
return 0, err
}
2023-02-19 18:20:25 -06:00
resp.Body.Close()
2023-02-19 13:44:18 -06:00
return resp.StatusCode, nil
}
var pingCmd = &cobra.Command{
Use: "ping",
2023-02-19 18:20:25 -06:00
Short: "This pings a remote URL and returns the response",
Long: ``,
2023-02-19 13:44:18 -06:00
Run: func(cmd *cobra.Command, args []string) {
if resp, err := ping(urlPath); err != nil {
fmt.Println(err)
} else {
fmt.Println(resp)
}
},
}
func init() {
2023-02-19 18:20:25 -06:00
2023-02-19 13:44:18 -06:00
pingCmd.Flags().StringVarP(&urlPath, "url", "u", "", "The url to ping")
if err := pingCmd.MarkFlagRequired("url"); err != nil {
fmt.Println(err)
}
NetCmd.AddCommand(pingCmd)
}