Skip to main content

Go Project Setup Cheatsheet

· 2 min read

Create Executable Project

  1. Initialize a repo
# module path should be the same as the GitHub repo path
Go mod init github.com/username/reponame
# package files can be different from the module/repo name
# package name for entry point should be main
# e.g use a main.go for entry point
touch main.go

# write code
# e.g. package main and with a func main() {}
  1. Clean up dependencies
go mod tidy
  1. Build executable
go build
  1. Make executable available everywhere by installing it
# first find the install path of the package
# cd into the directory containing your entry point (main.go), typically your root
go list -f '{{.Target}}' # e.g. output /Users/username/go/bin/binaryname

# add the bin path to shell config
echo 'export PATH=$PATH:/Users/username/go/bin' >> ~/.zshrc
source ~/.zshrc # or omz reload for oh-my-zsh users

# install the package into the target location
go install

# verify successful
which binaryname

Create Module

  1. Initialize a repo
# module path should be the same as the GitHub repo path
Go mod init github.com/username/reponame
# package files can be different from the module/repo name
# package names can be different from module name
touch reponame.go

# write code
# e.g. package reponame and with public function
  1. Clean up dependencies
go mod tidy
  1. Create a git tag for a new release
git tag v0.1.0
git push origin v0.1.0

## check if the module is now available to the public
go list -m github.com/username/reponame@v0.1.0

Using the Module

  1. Remote Go project using the published module
go get github.com/username/reponame@v0.1.0
# use by importing github.com/username/reponame
# then, use by calling the wanted package.function()
  1. Local Go project using the local module
# assume caller is in another folder besides reponame folder
go mod edit -replace github.com/username/reponame=../reponame