| 1 | --- |
| 2 | tags: |
| 3 | - v3 |
| 4 | search: |
| 5 | boost: 2 |
| 6 | --- |
| 7 | |
| 8 | One of the philosophies behind cli is that an API should be playful and full of |
| 9 | discovery. So a cli app can be as little as one line of code in `main()`. |
| 10 | |
| 11 | <!-- { |
| 12 | "args": ["--help"], |
| 13 | "output": "A new cli application" |
| 14 | } --> |
| 15 | ```go |
| 16 | package main |
| 17 | |
| 18 | import ( |
| 19 | "os" |
| 20 | "context" |
| 21 | |
| 22 | "github.com/urfave/cli/v3" |
| 23 | ) |
| 24 | |
| 25 | func main() { |
| 26 | (&cli.Command{}).Run(context.Background(), os.Args) |
| 27 | } |
| 28 | ``` |
| 29 | |
| 30 | This app will run and show help text, but is not very useful. |
| 31 | |
| 32 | ``` |
| 33 | $ wl-paste > hello.go |
| 34 | $ go build hello.go |
| 35 | $ ./hello |
| 36 | NAME: |
| 37 | hello - A new cli application |
| 38 | |
| 39 | USAGE: |
| 40 | hello [global options] |
| 41 | |
| 42 | GLOBAL OPTIONS: |
| 43 | --help, -h show help |
| 44 | ``` |
| 45 | |
| 46 | Let's add an action to execute and some help documentation: |
| 47 | |
| 48 | <!-- { |
| 49 | "output": "boom! I say!" |
| 50 | } --> |
| 51 | ```go |
| 52 | package main |
| 53 | |
| 54 | import ( |
| 55 | "fmt" |
| 56 | "log" |
| 57 | "os" |
| 58 | "context" |
| 59 | |
| 60 | "github.com/urfave/cli/v3" |
| 61 | ) |
| 62 | |
| 63 | func main() { |
| 64 | cmd := &cli.Command{ |
| 65 | Name: "boom", |
| 66 | Usage: "make an explosive entrance", |
| 67 | Action: func(context.Context, *cli.Command) error { |
| 68 | fmt.Println("boom! I say!") |
| 69 | return nil |
| 70 | }, |
| 71 | } |
| 72 | |
| 73 | if err := cmd.Run(context.Background(), os.Args); err != nil { |
| 74 | log.Fatal(err) |
| 75 | } |
| 76 | } |
| 77 | ``` |
| 78 | The output of above code is |
| 79 | |
| 80 | ``` |
| 81 | boom! I say! |
| 82 | ``` |
| 83 | |
| 84 | Running this already gives you a ton of functionality, plus support for things |
| 85 | like subcommands and flags, which are covered in a separate section. |