Created
July 4, 2015 15:50
-
-
Save iamralch/a6f02026270b443d5e46 to your computer and use it in GitHub Desktop.
flag package: subcommand example
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main | |
import ( | |
"flag" | |
"fmt" | |
"os" | |
) | |
func main() { | |
askCommand := flag.NewFlagSet("ask", flag.ExitOnError) | |
questionFlag := askCommand.String("question", "", "Question that you are asking for.") | |
sendCommand := flag.NewFlagSet("send", flag.ExitOnError) | |
recipientFlag := sendCommand.String("recipient", "", "Recipient of your message.") | |
messageFlag := sendCommand.String("message", "", "Text message.") | |
if len(os.Args) == 1 { | |
fmt.Println("usage: siri <command> [<args>]") | |
fmt.Println("The most commonly used git commands are: ") | |
fmt.Println(" ask Ask questions") | |
fmt.Println(" send Send messages to your contacts") | |
return | |
} | |
switch os.Args[1] { | |
case "ask": | |
askCommand.Parse(os.Args[2:]) | |
case "send": | |
sendCommand.Parse(os.Args[2:]) | |
default: | |
fmt.Printf("%q is not valid command.\n", os.Args[1]) | |
os.Exit(2) | |
} | |
if askCommand.Parsed() { | |
if *questionFlag == "" { | |
fmt.Println("Please supply the question using -question option.") | |
return | |
} | |
fmt.Printf("You asked: %q\n", *questionFlag) | |
} | |
if sendCommand.Parsed() { | |
if *recipientFlag == "" { | |
fmt.Println("Please supply the recipient using -recipient option.") | |
return | |
} | |
if *messageFlag == "" { | |
fmt.Println("Please supply the message using -message option.") | |
return | |
} | |
fmt.Printf("Your message is sent to %q.\n", *recipientFlag) | |
fmt.Printf("Message: %q.\n", *messageFlag) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
It would have been good if the help or usage text is somehow derived/specified as part of subcommand definition. Not sure if one exists.