Go by Example: Command-Line Subcommands

The following example demonstrates how to use subcommands in Go:

package main

import (
	"flag"
	"fmt"
	"os"
)

func main() {
	cmd := flag.NewFlagSet("create", flag.ExitOnError)
	createName := cmd.String("name", "", "Name of the resource to create")

	cmd2 := flag.NewFlagSet("delete", flag.ExitOnError)
	deleteName := cmd2.String("name", "", "Name of the resource to delete")

	if len(os.Args) < 2 {
		fmt.Println("expected 'create' or 'delete' subcommands")
		os.Exit(1)
	}

	switch os.Args[1] {
	case "create":
		cmd.Parse(os.Args[2:])
		fmt.Println("Creating resource:", *createName)
	case "delete":
		cmd2.Parse(os.Args[2:])
		fmt.Println("Deleting resource:", *deleteName)
	default:
		fmt.Println("expected 'create' or 'delete' subcommands")
		os.Exit(1)
	}
}

In this example, we use the flag.NewFlagSet function to create two different sets of flags, one for each of our two subcommands create and delete. We then use a switch statement to parse the subcommand and set the corresponding flags. Finally, we use the values of the flags to take appropriate action.

Here’s an example run of the program:

$ go run main.go create --name=test
Creating resource: test

Comments

Leave a Reply

Your email address will not be published. Required fields are marked *