music-token-cli
cli written in go (with cobra) that consumes information about albums, songs and artists from spotify API endpoints using the provided JWT
How to create a cli in go with cobra
Create the go project
go mod init my project
Install cobra
go get -u github.com/spf13/cobra/cobra
Create the cobra boilerplate
cobra init --pkg-name my project
Add commands to the cli
cobra add my-new-command
Adding subcommands
To add a subcommand execute the same cobra command to add a new command.
Then go to the file you want to be the primary command of this new command.
Edit the init method with the primary command.
func init() {
artistCmd.AddCommand(bynameCmd)
}
The easy way:
cobra add name -p "artistCmd"
Adding flags
Global flags are in root.go
Local flags go in the respective command
Running the cli
To build a particular command use
go run . my-project subcommand1 subcommand2
Build the project & running as binary
go build -o my-project
./my-project
Troubleshooting
cobra: command not found
vi ~/.zshrc
export GOPATH=$HOME/go
export GOBIN=$GOPATH/bin
export PATH=${PATH}:$GOBIN
source ~/.zshrc
NOTE: Always use camel case rather than snake case because that may lead to errors