Skip to content

Instantly share code, notes, and snippets.

@SuperMatt
Created August 9, 2017 14:32
Show Gist options
  • Save SuperMatt/73d80e0e07580f4ba2271e74ede60f01 to your computer and use it in GitHub Desktop.
Save SuperMatt/73d80e0e07580f4ba2271e74ede60f01 to your computer and use it in GitHub Desktop.
How to use flags with subcommands.
package main
import (
"flag"
"fmt"
"os"
)
func main() {
verbose := flag.Bool("v", false, "verbose mode")
prnt := flag.NewFlagSet("print", flag.ExitOnError)
prntstrng := prnt.String("s", "", "string to print")
prnt.Usage = func() {
fmt.Fprintf(os.Stderr, "Usage of %s:\n", os.Args[0])
flag.PrintDefaults()
fmt.Fprintf(os.Stderr, "Usage of prnt:\n")
prnt.PrintDefaults()
}
flag.Parse()
switch flag.Args()[0] {
case "help":
fmt.Println("Usage of", os.Args[0])
fmt.Println("\thelp\t\tThis command")
case "prnt":
prnt.Parse(flag.Args()[1:])
}
fmt.Println(*verbose, *prntstrng)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment