Go Project Setup Cheatsheet
· 2 min read
Create Executable Project
- 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() {}
- Clean up dependencies
go mod tidy
- Build executable
go build
- 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
- 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
- Clean up dependencies
go mod tidy
- 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
- 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()
- 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