func main() { app := cli.NewApp() app.Flags = []cli.Flag{ &cli.BoolFlag{ Name: "debug", Usage: "enable debug mode", }, } app.Action = func(c *cli.Context) error { if c.Bool("debug") { fmt.Println("Debug mode is enabled") } else { fmt.Println("Debug mode is disabled") } return nil } err := app.Run(os.Args) if err != nil { log.Fatal(err) } }
func main() { app := cli.NewApp() app.Commands = []*cli.Command{ { Name: "serve", Usage: "start the server", Flags: []cli.Flag{ &cli.StringFlag{ Name: "port", Usage: "port to listen on", Value: "8080", }, }, Action: func(c *cli.Context) error { if c.IsSet("port") { fmt.Printf("Starting server on port %s\n", c.String("port")) } else { fmt.Println("Starting server on default port 8080") } return nil }, }, } err := app.Run(os.Args) if err != nil { log.Fatal(err) } }In this example, we define a subcommand called "serve" that starts a server. We define a command-specific string flag called "port" with a default value of 8080. Inside the subcommand's Action function, we check if the "port" flag is set using the Context IsSet method and print the appropriate message. Overall, the "github.com/urfave/cli" package is a useful library in Go for building command-line applications, and the Context IsSet function is a handy method for checking the status of flags and arguments.