This is the next step for a Go developer after playing with the flag package. It provides an intuitive API for creating command-line applications with ease. It allows us to collect arguments and flags. It could be quite handy for designing complex applications. To install the package, use the following command:
go get github.com/urfave/cli
After that, let us write a program that does exactly the same job as the preceding programs:
cli/cliBasic.go:
package main import ( "log" "os" "github.com/urfave/cli" ) func main() { // Create new app app := cli.NewApp() // add flags with three arguments app.Flags = []cli.Flag { cli.StringFlag{ Name: "name", Value: "stranger", Usage: "your wonderful name", }, cli.IntFlag{ Name: "age", Value: 0, Usage: "your graceful age", }, } // This function parses and brings data in cli.Context struct app.Action = func(c *cli.Context) error { // c.String, c.Int looks for value of given flag log.Printf("Hello %s (%d years), Welcome to the command line world", c.String("name"), c.Int("age")) return nil } // Pass os.Args to cli app to parse content app.Run(os.Args) }
This is lengthier than the one before, but it is more expressive. We created a new app using the cli.NewApp function. It creates a new struct. We need to attach a few parameters to this struct. They are the Flags struct and the Action function. The Flags struct is a list that defines all possible flags for this application. The structure of Flag from GoDoc (https://godoc.org/github.com/urfave/cli#Flag) is:
type Flag interface {
fmt.Stringer
// Apply Flag settings to the given flag set
Apply(*flag.FlagSet)
GetName() string
}
The inbuilt structs, such as StringFlag and IntFlag, implement this Flag interface. Name, Value, and Usage are straightforward. They are similar to the ones used in the flag package. The Action function takes the argument cli.Context. That context object holds all of the information about flags and command-line arguments. We can use them and apply logic to them. The c.String, c.Int, and other functions are used to look up the flag variables. For example, in the preceding program, c.String("name") fetches a flag variable whose name is name. This program runs the same as the previous programs:
go build cli/cliBasic.go