7

Create a Golang CLI in Minutes with Cobra

 2 years ago
source link: https://blog.jongallant.com/2021/08/golang-cli-cobra/?utm_campaign=Feed%3A+jongallant+%28Jon+Gallant%29
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

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

wget -q -O - https://git.io/vQhTU | bash

Obv is you aren’t comfortable with that, install from here: 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://github.com/spf13/cobra

And it has a CLI Generator:
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.

# 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

Troubleshooting:

If you get this error:

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'

Then you need to run this in your project dir:

go mod init github.com/jongio/app

3. Run It

Run this:

go run main.go

And you’ll see this:

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.

"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:

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.


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK