Cobra Command Line using Go

Share on:

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
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
  1. Make the go home directory

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

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

Install Cobra

  1. We can use Go to download and build a local Cobra binary
1go 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:

1.
2├── go.mod
3└── go.sum

Integrate Cobra

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

  2. Run the code hello application

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