package main import ( "os" "fmt" "github.com/mitchellh/cli" ) func main() { // Define a CLI application c := cli.NewCLI("myapp", "1.0.0") c.Args = os.Args[1:] // Define a command c.Commands = map[string]cli.CommandFactory{ "hello": func() (cli.Command, error) { return &HelloCommand{}, nil }, } // Start the CLI application exitCode, err := c.Run() if err != nil { fmt.Println(err) } os.Exit(exitCode) } type HelloCommand struct{} func (c *HelloCommand) Help() string { return "Say hello" } func (c *HelloCommand) Run(args []string) int { fmt.Println("Hello world!") return 0 } func (c *HelloCommand) Synopsis() string { return "Say hello" }
package main import ( "os" "fmt" "github.com/mitchellh/cli" ) func main() { c := cli.NewCLI("myapp", "1.0.0") c.Args = os.Args[1:] // Define a command that prompts the user for input c.Commands = map[string]cli.CommandFactory{ "greet": func() (cli.Command, error) { return &GreetCommand{}, nil }, } exitCode, err := c.Run() if err != nil { fmt.Println(err) } os.Exit(exitCode) } type GreetCommand struct{} func (c *GreetCommand) Help() string { return "Greet someone by name" } func (c *GreetCommand) Run(args []string) int { ui := &cli.BasicUi{ Reader: os.Stdin, Writer: os.Stdout, ErrorWriter: os.Stderr, } name, err := ui.Ask("What's your name?") if err != nil { ui.Error(err.Error()) return 1 } fmt.Printf("Hello, %s!\n", name) return 0 } func (c *GreetCommand) Synopsis() string { return "Greet someone by name" }This code demonstrates a command "greet" that prompts the user for their name and then says hello to them. The prompt-based user input is handled by the cli.BasicUi struct.