Folder structure for Golang on development machines.

30th November 2015

Why does it matter?

Many development tools don’t care how you organise your folders. Go is not one of them.

If your folders are not quite right, things don’t build. Or they don’t place dependencies in sensible places. Or go install doesn’t put your built binaries in a helpful place. Or [insert other bad stuff here].

The $GOPATH variable.

Before continuing, you should be aware that Go will not build anything without a $GOPATH environment variable [not quite true anymore, but still advisable anyway]. It uses this as a top level folder for:

  • finding source code subfolders
  • downloading packages (go get)
  • linking in fetched packages
  • knowing where to place install binaries

I’m on a Mac and so everything that follows is OSX-specific. However, the principles are the same on Linux. If you’re doing Go development on Windows then I’d suggest you get a Linux VM and use that instead (Linux Mint is especially good).

The folder structure.

Recommended layout.

Obviously the repository providers, account names and code folders will vary.

/home/karl/Documents
  /GoLang
    /bin
    /pkg
    /src
      /bitbucket.org
        /kcartlidge
          /project1
          /project2
      /github.com
        /kacartlidge
          /project3
          /project4

Making life easier.

When I follow this pattern, I also update my Terminal preferences to run the following command on start:

export GOPATH=~/Documents/GoLang

This is in the Terminal, Preferences, Shell option.

Step by step.

  • Create the folder structure first, down to the account name for your repositories (e.g. kacartlidge), but don’t create project subfolders.
  • Run a git clone command in the account name folder and a project subfolder will be created for the code you pull down.
  • In your project folder run go get and the Go compiler will fetch all dependencies into the same src folder tree your own code sits in, and will also populate the pkg folder as needed.
  • In your newly-cloned project subfolder run either go build or go install to build a binary. The former will place the executable in the project folder and the latter into the bin folder near the top of your folder structure.

Regardless of your project, go install will always place the generated binary in the same $GOPATH/bin subfolder. You can therefore make that folder available everywhere so you can get access to your own binaries from any command prompt. The easiest way to do this is to update your list of paths:

sudo vi /etc/paths

Just add the $GOPATH/bin to that file and restart your Terminal session.

In Linux or Windows you can get a similar outcome by updating your system PATH environment variable.