Design subcommands and help
Design subcommands and help
A subcommand names a specific operation such as show or export. Dispatch on the first argument, then give each operation its own FlagSet and usage text. Keep a testable command function that receives arguments and output writers. The return value is the proposed exit status, not a process exit yet.
package main
import ( "errors" "flag" "fmt" "io" "os")
func command(args []string, out, errOut io.Writer) int { if len(args) == 0 || args[0] == "help" { fmt.Fprintln(out, "usage: tool show [-name VALUE]") return 0 } if args[0] != "show" { fmt.Fprintln(errOut, "unknown command") return 2 } f := flag.NewFlagSet("show", flag.ContinueOnError) f.SetOutput(errOut) name := f.String("name", "guest", "display name") f.Usage = func() { fmt.Fprintln(errOut, "usage: tool show [-name VALUE]") } if err := f.Parse(args[1:]); err != nil { if errors.Is(err, flag.ErrHelp) { return 0 } return 2 } if f.NArg() != 0 { fmt.Fprintln(errOut, "unexpected operand") return 2 } fmt.Fprintln(out, *name) return 0}func main() { fmt.Println("status:", command([]string{"show", "-name", "Nila"}, os.Stdout, os.Stderr))}Top-level dispatch prevents flags belonging to different commands from interfering. Here no arguments and help intentionally print general usage with status zero. Unknown commands and unexpected operands use status two by local convention. Write help for each accepted operation and document whether global flags precede subcommands.
Expected output:
Nilastatus: 0Handle help without exiting
package main
import ( "bytes" "errors" "flag" "fmt" "io" "strings")
func command(args []string, out, errOut io.Writer) int { if len(args) == 0 || args[0] == "help" { fmt.Fprintln(out, "usage: tool show [-name VALUE]") return 0 } if args[0] != "show" { fmt.Fprintln(errOut, "unknown command") return 2 } f := flag.NewFlagSet("show", flag.ContinueOnError) f.SetOutput(errOut) name := f.String("name", "guest", "display name") f.Usage = func() { fmt.Fprintln(errOut, "usage: tool show [-name VALUE]") } if err := f.Parse(args[1:]); err != nil { if errors.Is(err, flag.ErrHelp) { return 0 } return 2 } if f.NArg() != 0 { fmt.Fprintln(errOut, "unexpected operand") return 2 } fmt.Fprintln(out, *name) return 0}func main() { var out, diag bytes.Buffer code := command([]string{"show", "-h"}, &out, &diag) fmt.Println(code, out.Len() == 0, strings.Contains(diag.String(), "usage:"))}When no h/help flag is explicitly registered, the flag package calls Usage and returns ErrHelp for -h or -help. ContinueOnError leaves the status decision to the caller. This example sends subcommand help to the diagnostic writer; a CLI may choose stdout for explicitly requested help, but should document and test that choice.
Expected output:
0 true trueTry it locally
Call command with an unknown subcommand and two buffers. Print the status, whether stdout is empty and whether the diagnostic contains unknown command.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
CLI 02: Design subcommands and help
Check the lesson objective before moving on.
Why create a separate FlagSet per subcommand?
How should explicitly requested help normally finish?