-
-
Save hnakamur/2512fd35b8e0b41d2c08 to your computer and use it in GitHub Desktop.
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" | |
) | |
var usage = `Usage argtest [Globals] <Command> [Options] | |
Commands: | |
put Put something | |
get Get something | |
Globals Options: | |
` | |
var subcommandOptionsUsageFormat = "\nOptions for subcommand \"%s\":\n" | |
func subcommandUsageFunc(subcommand string, fs *flag.FlagSet) func() { | |
return func() { | |
flag.Usage() | |
fmt.Printf(subcommandOptionsUsageFormat, subcommand) | |
fs.PrintDefaults() | |
} | |
} | |
func main() { | |
var ( | |
opt1 = flag.String("opt1", "default-value", "First string option") | |
opt2 = flag.String("opt2", "default-value", "Second string option") | |
) | |
flag.Usage = func() { | |
fmt.Print(usage) | |
flag.PrintDefaults() | |
} | |
flag.Parse() | |
args := flag.Args() | |
if len(args) == 0 { | |
flag.Usage() | |
os.Exit(1) | |
} | |
fmt.Println("opt1:", *opt1) | |
fmt.Println("opt2:", *opt2) | |
switch args[0] { | |
case "put": | |
PutCommand(args[1:]) | |
case "get": | |
GetCommand(args[1:]) | |
default: | |
flag.Usage() | |
os.Exit(1) | |
} | |
} | |
func PutCommand(args []string) { | |
fs := flag.NewFlagSet("put", flag.ExitOnError) | |
putOpt := fs.String("put-opt", "default-value", "Put option") | |
fs.Usage = subcommandUsageFunc("put", fs) | |
fs.Parse(args) | |
if len(args) == 0 { | |
fs.Usage() | |
os.Exit(1) | |
} | |
fmt.Println("args:", fs.Args()) | |
fmt.Println("putopt:", *putOpt) | |
} | |
func GetCommand(args []string) { | |
fs := flag.NewFlagSet("get", flag.ExitOnError) | |
getOpt := fs.String("get-opt", "default-value", "Get option") | |
fs.Usage = subcommandUsageFunc("get", fs) | |
fs.Parse(args) | |
if len(args) == 0 { | |
fs.Usage() | |
os.Exit(1) | |
} | |
fmt.Println("args:", fs.Args()) | |
fmt.Println("getopt:", *getOpt) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Here are example usage outputs: