Introduction to Go workspaces

By

An introduction to the Go workspace and GOPATH, the $HOME/go home base where Go installs the packages and tooling your projects depend on.

~~~

One special thing about Go is what we call workspace. The workspace is the “home base” for Go: a single folder where Go stores the tools you install and the packages your projects depend on.

By default Go picks the $HOME/go path, so you will see a go folder in your home.

You don’t create it yourself. It appears the first time you install a package, or when your editor installs some tooling. For example the moment I loaded the hello.go file in VS Code, it prompted me to install the gopls command, the Delve debugger (dlv) and the staticcheck linter.

They were automatically installed under $HOME/go:

Screen Shot 2022-07-28 at 12.27.27.png

What’s inside the workspace?

Look inside the folder and you’ll find two main directories.

bin holds the executables. When you install a tool with go install, the compiled binary ends up here:

go install golang.org/x/tools/gopls@latest

After this command you’ll find a gopls executable in $HOME/go/bin.

pkg holds the module cache, under pkg/mod. When you add a dependency to a project and run go mod tidy or go build, Go downloads the source code of that dependency here. Every project on your machine shares this cache, so the same version of a library is only downloaded once.

What is GOPATH?

The location of this workspace is what we call GOPATH.

You can ask Go where it currently points:

go env GOPATH

On my Mac this prints /Users/flavio/go.

You can change the GOPATH environment variable to change where Go should install packages.

This is useful when working on different projects at the same time and you want to isolate the libraries you use.

A common problem

Here’s a pitfall almost everyone hits. You install a tool:

go install golang.org/x/tools/gopls@latest

then you run gopls and the shell says command not found.

The binary is there, in $HOME/go/bin, but that folder is not in your PATH, so the shell can’t find it. The fix is to add it to your shell configuration, for example in ~/.zshrc:

export PATH=$PATH:$HOME/go/bin

Open a new terminal and the command works.

One last note: the module cache can grow a lot over time. If you want to reclaim disk space, you can clear it with go clean -modcache and Go will re-download what your projects need on the next build.

Tagged: Go · All topics

Want me to talk about your product? You can sponsor this site.

~~~

Related posts about go: