(Q2 2018:
Note that with the vgo (now “module”) project, GOPATH might end up being deprecated in favor of a project-based workflow. That would avoid the manual project-based GOPATH I was proposing below, two years ago)
With Go 1.11 (August 2018), GOPATH can be optional, with modules.
You have a similar idea expressed in Manage multiple GOPATH dirs with ease, by Herbert Fischer (hgfischer), for a Linux/Unix environment (base on the question already mention in the comments above):
Just include the following snippet in your
~/.bashrc(or~/.bash_profile) and reload your shell environment withsource ~/.bashrc.
This snippet will create a shell function that will override the builtin commandcdwith a customized one that scans the entered directory, and every other above, for a file named.gopath.
cd () {
builtin cd "$@"
cdir=$PWD
while [ "$cdir" != "https://stackoverflow.com/" ]; do
if [ -e "$cdir/.gopath" ]; then
export GOPATH=$cdir
break
fi
cdir=$(dirname "$cdir")
done
}
Now you just need to create a
.gopathfile in every directory you want as yourGOPATHand every time you enter this directory, the redefinedcdfunction will set theGOPATHof your current environment to this directory.
Update 2017: if you don’t want to modify your environment, you can still use one GOPATH per project, by opening the src folder of that project in Visual Studio Code (vscode, which is a multi-platform IDE), combined with the extension “Go for Visual Studio Code”.
In that IDE, you can:
- keep your global unique
GOPATHin a setting calledgo.toolsGopath. - infer your current
GOPATHwith a setting calledgo.inferGopath

That way, VSCode will install a collection of tools in your global GOPATH (for you to use outside VSCode as well).
See “Go tools that the Go extension depends on”: godep, golint, guru, godoc, …
And yet, your GOPATH for your project will be the parent folder of src:

That works when you compile/install your project from the IDE.
If you want to do it from the command line, the original answer above would still apply.