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.
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
And it has a CLI Generator:
Here’s how to use it:
appwith 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
If you get this error:
[email protected]:~/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
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.
The cobra generate also has helpers to easily add new commands:
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
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.