How to group related command-line flags and options using subcommands in Go?

In Go, you can group related command-line flags and options using subcommands by utilizing the flag and flag.FlagSet package. Here's how you can do it:

  1. First, import the necessary packages:
import ( "flag" "fmt" "os" )
  1. Create a struct for each subcommand, including related flags and options:
type SubcommandA struct { fs *flag.FlagSet flag1 string flag2 int } type SubcommandB struct { fs *flag.FlagSet flag3 bool flag4 float64 }
  1. Implement the init function for each subcommand to initialize the flag set and bind flags to struct fields:
func (s *SubcommandA) init() { s.fs = flag.NewFlagSet("subcommandA", flag.ExitOnError) s.fs.StringVar(&s.flag1, "flag1", "", "Description for flag1") s.fs.IntVar(&s.flag2, "flag2", 0, "Description for flag2") } func (s *SubcommandB) init() { s.fs = flag.NewFlagSet("subcommandB", flag.ExitOnError) s.fs.BoolVar(&s.flag3, "flag3", false, "Description for flag3") s.fs.Float64Var(&s.flag4, "flag4", 0.0, "Description for flag4") }
  1. Implement a function to parse the command-line arguments and execute the appropriate subcommand:
func parseArgs() { if len(os.Args) < 2 { fmt.Println("Usage: <executable> subcommand [arguments]") os.Exit(1) } switch os.Args[1] { case "subcommandA": subcommandA := &SubcommandA{} subcommandA.init() subcommandA.fs.Parse(os.Args[2:]) // Execute logic for subcommandA case "subcommandB": subcommandB := &SubcommandB{} subcommandB.init() subcommandB.fs.Parse(os.Args[2:]) // Execute logic for subcommandB default: fmt.Println("Invalid subcommand") os.Exit(1) } }
  1. Call the parseArgs function in your main function to handle the command-line arguments:
func main() { parseArgs() // Add your main program logic here }

With this setup, you can define multiple subcommands, each with its own set of flags and options, and execute different logic based on the selected subcommand when running your Go application from the command line.