Created
April 26, 2022 20:20
-
-
Save dav-m85/4a6ca2012e41db9ab8fda9ae909e8ca1 to your computer and use it in GitHub Desktop.
Idiomatic Golang Subcommands
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
// 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