Cobra Command Line using Go
The Go programming language is an open source project to make programmers more productive. In the following blog post I assume you already have the Go environment setup. Previously we have created a Hello World application. The next step is to create a command line application. The example below covers the basics of using Cobra
Go Installation
- Confirm Go is installed
1go version
If it is not installed check out a previous post to install Go in Linux
Development setup
With go already installed, the setup requires a couple more steps
- Create a directory for your code
- Initialise the location where the module can be found
-
Make the go home directory
1mkdir -p ~/hello_cobra && cd hello_cobra
-
Initialise the hello directory
1go mod init github.com/rosera/hello_cobra
- The directory should now look like this:
1.
2└── go.mod
Install Cobra
- We can use Go to download and build a local
Cobra
binary
1go get -u github.com/spf13/cobra/cobra
-
The binary for
Cobra
will now be available in theGo
bin path. -
The directory should now look like this:
1.
2├── go.mod
3└── go.sum
Integrate Cobra
- Add
Cobra
to the existing app
1cobra init
- The directory should now look like this:
1.
2├── cmd
3│ └── root.go
4├── go.mod
5├── go.sum
6├── LICENSE
7└── main.go
- Build the application
1go build
-
The build command will produce an application based on the folder name
-
Run the code hello application
1./hello_cobra
- The application output should be as per below:
1A longer description that spans multiple lines and likely contains
2examples and usage of using your application. For example:
3
4Cobra is a CLI library for Go that empowers applications.
5This application is a tool to generate the needed files
6to quickly create a Cobra application.