Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
package main
import (
"fmt"
"flag"
"os"
)
var usage =
`Usage argtest [Globals] <Command> [Options]
Commands:
put Put something
get Get something
Globals:
-opt1=default-value First string option
-opt2=default-value Second string option
`
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.Parse()
fmt.Println("opt1:", *opt1)
fmt.Println("opt2:", *opt2)
args := flag.Args()
if len(args) == 0 {
flag.Usage()
os.Exit(1)
}
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.Parse(args)
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.Parse(args)
fmt.Println("args:", fs.Args())
fmt.Println("getopt:", *getOpt)
}
@matope

This comment has been minimized.

Copy link
Owner Author

matope commented Mar 9, 2014

グローバルオプションopt1と、サブコマンドput

./subcommand -opt1=XXX put -put-opt=YYY BBB CCC
opt1: XXX
opt2: default-value
args: [BBB CCC]
putopt: YYY
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.