Dec 26, 2021 • 2 min read
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
go versionIf 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
NODE_TYPE // bashmkdir -p ~/hello_cobra && cd hello_cobra -
Initialise the hello directory
go mod init github.com/rosera/hello_cobra- The directory should now look like this:
.
└── go.modInstall Cobra
- We can use Go to download and build a local
Cobrabinary
go get -u github.com/spf13/cobra/cobra-
The binary for
Cobrawill now be available in theGobin path. -
The directory should now look like this:
.
├── go.mod
└── go.sumIntegrate Cobra
- Add
Cobrato the existing app
cobra init- The directory should now look like this:
.
├── cmd
│ └── root.go
├── go.mod
├── go.sum
├── LICENSE
└── main.go- Build the application
go build-
The build command will produce an application based on the folder name
-
Run the code hello application
./hello_cobra- The application output should be as per below:
A longer description that spans multiple lines and likely contains
examples and usage of using your application. For example:
Cobra is a CLI library for Go that empowers applications.
This application is a tool to generate the needed files
to quickly create a Cobra application.