...

/

Understanding the Cobra Generator

Understanding the Cobra Generator

You'll learn about the Cobra generator and use the Cobra generator to generate an application skeleton from scratch in this lesson.

The Cobra generator is another good way to utilize Cobra if you want to benefit from its established best practices and conventions.

What is the Cobra generator?

The generator is a command-line program that comes with Cobra. You can install it using the go tool

$ go get github.com/spf13/cobra/cobra/...

After you install Cobra it should be on your path. Try it out in the terminal below. Just type cobra

Terminal 1
Terminal
Loading...

As you can see, the cobra program has two primary commands other than help:

  1. init
  2. add

How does the Cobra generator work?

The Cobra generator works by generating directories and files for you that follow best practices. As you probably guessed, the Cobra generator is itself a Cobra CLI application. It follows the standard structure, having a root command and two actual commands for init and add.

It’s a good idea to dive in a little deeper as it is a great example of using Cobra from the Cobra developer. The code is available here:

https://github.com/spf13/cobra/blob/master/cobra

Here is a snippet from the root command:

func
...