Jon Gallant

Create a Golang CLI in Minutes with Cobra

2 min read

"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: https://github.com/canha/golang-tools-install-script

Terminal window
wget -q -O - https://git.io/vQhTU | bash
```python
Obv is you aren’t comfortable with that, install from here: [https://golang.org/doc/install](https://golang.org/doc/install)
## 2. Install Cobra (CLI Tool)
Cobra is a module that helps you create Golang CLI apps: [https://cobra.dev/](https://cobra.dev/) & [https://github.com/spf13/cobra](https://github.com/spf13/cobra)
And it has a CLI Generator:
[https://github.com/spf13/cobra/blob/master/cobra/README.md](https://github.com/spf13/cobra/blob/master/cobra/README.md)
Here’s how to use it:
> Note: Replace `jongio` and `app` with your own names.
```bash
# Get the CLI Generator
go get github.com/spf13/cobra/cobra
# Create dir for your app
mkdir -p app && cd app
# Initialize the go module
go mod init github.com/jongio/app
# Initialize the CLI project with cobra
cobra init --pkg-name github.com/jongio/app
# Get the cobra/viper dependencies. This will add to your go.mod file
go get github.com/spf13/cobra
go get github.com/spf13/viper
# Build to make sure we are good.
go build
```markdown
- *Troubleshooting:**
If you get this error:
```text
jon@JONGWFH:~/app$ go run main.go
main.go:18:8: no required module provides package github.com/jongio/app/cmd: go.mod file not found in current directory or any parent directory; see 'go help modules'
```text
Then you need to run this in your project dir:
```bash
go mod init github.com/jongio/app
```markdown
## 3. Run It
Run this:
```bash
go run main.go
```text
And you’ll see this:
```bash
jon@JONGWFH:~/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.
```csharp
!["CLI default Output"](/images/golang-cli-cobra/105.png)
## 4. Add a Command
The cobra generate also has helpers to easily add new commands:
Add command:
```bash
cobra add login
```csharp
Run new command:
```bash
go run main.go login
```text
And you’ll see:
```bash
jon@JONGWFH:~/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: https://marketplace.visualstudio.com/items?itemName=golang.Go

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

Jon

Share:
Share on X