Golang project quick start

Posted in tech; tagged with golang, tips

HOWTO: Create a basic Golang command line app structure using Cobra and opinions.

FYI See also: * Cobra: https://github.com/spf13/cobra * Cobra command line generation tool: https://github.com/spf13/cobra/blob/master/cobra/README.md

Objectives

  1. Standardize on how new Golang projects are created
  2. Make use of commonly used configuration and flag handling packages (Viper, Cobra)
  3. Automate where easy the creation of project structure (not at the level of scaffolding)
  4. Not be tied to any framework or use case, be useful info/tools for web apps or command line utilities.
  5. Make use of current practice including Go Modules

Install First

Cobra (which will pull in Viper):

go get github.com/spf13/cobra
# command line generator
go get github.com/spf13/cobra/cobra

To avoid repeating yourself on each use, create a ~/.cobra.yaml file with the contents:

author: Your Name <youremail@foo.com>
license: MIT

Create a new Go project/package

Since we are using Go Modules we don’t have to put this in our go/src/... space. For this example, creating a linkr package in my ~/project/ folder:

cd ~/project/
cobra init linkr --pkg-name linkr
cd linkr
echo "# linkr" >> README.md
go mod init linkr
# run the new "app" once to initially populate go.mod
go run main.go

Create a new, empty, repository on Github

Login to github and using the web UI create a new repo linkr. Copy the SSH string. Example:

# still within ~/project/linkr
git init 
git remote add origin git@github.com:solutionroute/linkr.git
git add .
git commit -m "First commit"
git push -u origin master