-
-
Save tetheredge/4cda1e1451be426af8af 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.") | |
questionShortFlag := askCommand.String("q", "", "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 == "" && *questionShortFlag == "" { | |
fmt.Println("Please supply the question using -question or -q option.") | |
return | |
} else if *questionFlag != "" { | |
fmt.Printf("\"%s?\""+"\n", *questionFlag) | |
return | |
} else { | |
fmt.Printf("\"%s?\""+"\n", *questionShortFlag) | |
return | |
} | |
} | |
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