Skip to content

Instantly share code, notes, and snippets.

@dav-m85
Created April 26, 2022 20:20
Show Gist options
  • Save dav-m85/4a6ca2012e41db9ab8fda9ae909e8ca1 to your computer and use it in GitHub Desktop.
Save dav-m85/4a6ca2012e41db9ab8fda9ae909e8ca1 to your computer and use it in GitHub Desktop.
Idiomatic Golang Subcommands
// Seen on https://stackoverflow.com/a/67905164
var (
required string
fooCmd = flag.NewFlagSet("foo", flag.ExitOnError)
barCmd = flag.NewFlagSet("bar", flag.ExitOnError)
)
var subcommands = map[string]*flag.FlagSet{
fooCmd.Name(): fooCmd,
barCmd.Name(): barCmd,
}
func setupCommonFlags() {
for _, fs := range subcommands {
fs.StringVar(
&required,
"required",
"",
"required for all commands",
)
}
}
func main() {
setupCommonFlags()
cmd := subcommands[os.Args[1]]
if cmd == nil {
log.Fatalf("[ERROR] unknown subcommand '%s', see help for more details.", os.Args[1])
}
cmd.Parse(os.Args[2:])
fmt.Println(cmd.Name())
if required == "" {
fmt.Println("-required is required for all commands")
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment