package main import ( "context" "fmt" "github.com/minio/cli" "os" ) func main() { app := cli.NewApp() app.Name = "myapp" app.Usage = "a CLI app" app.Action = func(ctx *cli.Context) error { fmt.Println("Hello, world!") return nil } err := app.RunContext(context.Background(), os.Args) if err != nil { fmt.Fprintln(os.Stderr, err) os.Exit(1) } }
package main import ( "context" "fmt" "github.com/minio/cli" "os" "os/signal" "syscall" ) func main() { app := cli.NewApp() app.Name = "myapp" app.Usage = "a CLI app" app.Action = func(ctx *cli.Context) error { fmt.Println("Press ^C to interrupt") select { case <-ctx.Done(): fmt.Println("Command interrupted") return ctx.Err() } return nil } // add signal handler sigch := make(chan os.Signal, 1) signal.Notify(sigch, syscall.SIGINT, syscall.SIGTERM) go func() { <-sigch fmt.Println("Interrupt signal received - shutting down") os.Exit(1) }() err := app.RunContext(context.Background(), os.Args) if err != nil { fmt.Fprintln(os.Stderr, err) os.Exit(1) } }This example sets up a CLI app that listens for `^C` (Ctrl+C) or `SIGTERM` signals to interrupt command execution. It uses the `ctx.Done()` method to detect if the command has been interrupted, and returns the context error if so. In both examples, the `github.com/minio/cli` package is used to set up and execute a command line interface with Go. The Context struct is used to provide cancellation functionality, allowing the program to react to user interrupts or other external events.