| 1 | --- |
| 2 | tags: |
| 3 | - v1 |
| 4 | --- |
| 5 | |
| 6 | Being a programmer can be a lonely job. Thankfully by the power of automation |
| 7 | that is not the case! Let's create a greeter app to fend off our demons of |
| 8 | loneliness! |
| 9 | |
| 10 | Start by creating a directory named `greet`, and within it, add a file, |
| 11 | `greet.go` with the following code in it: |
| 12 | |
| 13 | <!-- { |
| 14 | "output": "Hello friend!" |
| 15 | } --> |
| 16 | ``` go |
| 17 | package main |
| 18 | |
| 19 | import ( |
| 20 | "fmt" |
| 21 | "log" |
| 22 | "os" |
| 23 | |
| 24 | "github.com/urfave/cli" |
| 25 | ) |
| 26 | |
| 27 | func main() { |
| 28 | app := cli.NewApp() |
| 29 | app.Name = "greet" |
| 30 | app.Usage = "fight the loneliness!" |
| 31 | app.Action = func(c *cli.Context) error { |
| 32 | fmt.Println("Hello friend!") |
| 33 | return nil |
| 34 | } |
| 35 | |
| 36 | err := app.Run(os.Args) |
| 37 | if err != nil { |
| 38 | log.Fatal(err) |
| 39 | } |
| 40 | } |
| 41 | ``` |
| 42 | |
| 43 | Install our command to the `$GOPATH/bin` directory: |
| 44 | |
| 45 | ``` |
| 46 | $ go install |
| 47 | ``` |
| 48 | |
| 49 | Finally run our new command: |
| 50 | |
| 51 | ``` |
| 52 | $ greet |
| 53 | Hello friend! |
| 54 | ``` |
| 55 | |
| 56 | cli also generates neat help text: |
| 57 | |
| 58 | ``` |
| 59 | $ greet help |
| 60 | NAME: |
| 61 | greet - fight the loneliness! |
| 62 | |
| 63 | USAGE: |
| 64 | greet [global options] command [command options] [arguments...] |
| 65 | |
| 66 | VERSION: |
| 67 | 0.0.0 |
| 68 | |
| 69 | COMMANDS: |
| 70 | help, h Shows a list of commands or help for one command |
| 71 | |
| 72 | GLOBAL OPTIONS |
| 73 | --version Shows version information |
| 74 | ``` |