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