From ddbcb8ae97f9516e883b11fdebd950231bba00c6 Mon Sep 17 00:00:00 2001 From: dusanb Date: Fri, 27 Nov 2020 01:10:05 +0100 Subject: [PATCH] Add help menu Signed-off-by: dusanb --- README.md | 2 +- cmd/main.go | 38 +++++++++++++++++++++++++++++++++----- 2 files changed, 34 insertions(+), 6 deletions(-) diff --git a/README.md b/README.md index bb278ec..3601582 100644 --- a/README.md +++ b/README.md @@ -9,7 +9,7 @@ When running, please provide following format: | Flag | Description | Default value | | ---- | ---------------------------------------------- | ---------------- | -| o | observe option - only valid with Get request | false | +| o | observe option - only valid with GET request | false | | auth | auth option sent as URI Query | "" | | h | host | "localhost" | | p | port | "5683" | diff --git a/cmd/main.go b/cmd/main.go index 24fa79f..99b42e5 100644 --- a/cmd/main.go +++ b/cmd/main.go @@ -25,6 +25,25 @@ const ( delete = "DELETE" ) +const ( + helpCmd = `Use "coap-cli --help" for help.` + helpMsg = ` +Usage: coap-cli [options] +mathod: get, put, post or delete +-o observe option - only valid with GET request (default: false) +-auth auth option sent as URI Query (default: "") +-h host (default: "localhost") +-p port (default: "5683") +-d data to be sent in POST or PUT (default: "") +-cf content format (default: 50 - JSON format)) + +Examples: +coap-cli get channels/0bb5ba61-a66e-4972-bab6-26f19962678f/messages/subtopic -auth 1e1017e6-dee7-45b4-8a13-00e6afeb66eb -o +coap-cli post channels/0bb5ba61-a66e-4972-bab6-26f19962678f/messages/subtopic -auth 1e1017e6-dee7-45b4-8a13-00e6afeb66eb -d "hello world" +coap-cli post channels/0bb5ba61-a66e-4972-bab6-26f19962678f/messages/subtopic -auth 1e1017e6-dee7-45b4-8a13-00e6afeb66eb -d "hello world" -h 0.0.0.0 -p 1234 +` +) + func parseCode(code string) (codes.Code, error) { switch code { case get: @@ -47,18 +66,28 @@ func printMsg(m *pool.Message) { func main() { if len(os.Args) < 2 { - log.Fatal("Message code must be GET, PUT, POST or DELETE") + log.Fatal(helpCmd) + } + help := strings.ToLower(os.Args[1]) + if help == "-h" || help == "--help" { + log.Println(helpMsg) + os.Exit(0) } + code, err := parseCode(strings.ToUpper(os.Args[1])) if err != nil { - log.Fatal("error: ", err) + log.Fatalf("Can't read request code: %s\n%s", err, helpCmd) } + if len(os.Args) < 3 { - log.Fatal("Please enter valid CoAP URL") + log.Fatalf("CoAP URL must not be empty.\n%s", helpCmd) } path := os.Args[2] - os.Args = os.Args[2:] + if strings.HasPrefix(path, "-") { + log.Fatalf("Please enter a valid CoAP URL.\n%s", helpCmd) + } + os.Args = os.Args[2:] o := flag.Bool("o", false, "Observe") h := flag.String("h", "localhost", "Host") p := flag.String("p", "5683", "Port") @@ -66,7 +95,6 @@ func main() { cf := flag.Int("q", 50, "Content format") d := flag.String("d", "", "Message data") a := flag.String("auth", "", "Auth token") - flag.Parse() client, err := coap.New(*h + ":" + *p)