BACK TO THE HOMEPAGE

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

  1. Confirm Go is installed
go 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
  1. Make the go home directory

    mkdir -p ~/hello_cobra && cd hello_cobra
    
  2. Initialise the hello directory

go mod init github.com/rosera/hello_cobra
  1. The directory should now look like this:
.
└── go.mod

Install Cobra

  1. We can use Go to download and build a local Cobra binary
go get -u github.com/spf13/cobra/cobra
  1. The binary for Cobra will now be available in the Go bin path.

  2. The directory should now look like this:

.
├── go.mod
└── go.sum

Integrate Cobra

  1. Add Cobra to the existing app
cobra init
  1. The directory should now look like this:
.
├── cmd
│   └── root.go
├── go.mod
├── go.sum
├── LICENSE
└── main.go
  1. Build the application
go build
  1. The build command will produce an application based on the folder name

  2. Run the code hello application

./hello_cobra
  1. 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.