Command-Line Subcommands
flag.NewFlagSet creates a per-subcommand flag set, enabling tools with subcommands like "git commit" or "docker run" where each subcommand has its own flags.
flag.NewFlagSet creates a separate parser for one command. A subcommand is a named action such as tool list or tool delete. Read the first argument to choose the action, then parse the remaining arguments with that command's flag set.
Each subcommand can define its own flags and default values. Check that the user supplied a command before reading os.Args[1], the first user-supplied argument.
package main
import (
"flag"
"fmt"
"os"
)
func main() {
build := flag.NewFlagSet("build", flag.ExitOnError)
output := build.String("output", "app", "binary name")
if len(os.Args) < 2 {
fmt.Fprintln(os.Stderr, "usage: tool build [flags]")
os.Exit(1)
}
if os.Args[1] != "build" {
fmt.Fprintln(os.Stderr, "unknown command:", os.Args[1])
os.Exit(1)
}
build.Parse(os.Args[2:])
fmt.Println("building", *output, "with args", build.Args())
}In production
FlagSet is enough for a small command-line program. Put each command's behavior in a function that takes its arguments and returns an error. This makes the function easier to test without changing os.Args, which holds the arguments for the whole program.