Create a Golang CLI in Minutes with Cobra

"Golang CLI Cobra"

I’m new to Golang and yesterday I attempted to create a Golang CLI.

Here’s what I learned while getting it up and running on WSL.

This took me a while. Hopefully with this post it only takes you a few mins.

1. Install Go

You can install Golang using this one-liner script from:

wget -q -O - | bash

Obv is you aren’t comfortable with that, install from here:

2. Install Cobra (CLI Tool)

Cobra is a module that helps you create Golang CLI apps: &

And it has a CLI Generator:

Here’s how to use it:

Note: Replace jongio and app with your own names.

# Get the CLI Generator
go get
# Create dir for your app
mkdir -p app && cd app
# Initialize the go module
go mod init
# Initialize the CLI project with cobra
cobra init --pkg-name
# Get the cobra/viper dependencies. This will add to your go.mod file
go get
go get
# Build to make sure we are good.
go build


If you get this error:

[email protected]:~/app$ go run main.go
main.go:18:8: no required module provides package go.mod file not found in current directory or any parent directory; see 'go help modules'

Then you need to run this in your project dir:

go mod init

3. Run It

Run this:

go run main.go

And you’ll see this:

[email protected]:~/app$ go run main.go
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.

"CLI default Output"

4. Add a Command

The cobra generate also has helpers to easily add new commands:

Add command:

cobra add login

Run new command:

go run main.go login

And you’ll see:

[email protected]:~/app$ go run main.go login
login called

5. Golang VS Code Extension

I found this extension helpful to track down missing dependencies and what not:

That’s as far I’ve got with Golang, but it took me way longer than expected, so hope this helps you out.