Tuesday, February 27, 2018

Understanding the $gopath

One of the struggling issue for some newbies for golang is this $GOPATH.

Above are some of the issues that can cause from the $GOPATH. So It's always better to understand what the hell is this $GOPATH and simply how it works.

If you have already installed golang, open up a terminal or cmd and type 
> go env
go specific environment variables

Then it will show all the available environment variables that needs for the golang. Our only focus is to understand this $GOPATH. simply $GOPATH is a environment variable. 
  1. Is that it ? 
  2. What is it for ?

Look at my $GOPATH. I have set it to the C:\Users\User\go-projects

Sooooo is that means the $GOPATH == working directory ?
Actually if you think like that and set it to your working space will solve the problem. But how ?

Lets look at how a go project structure looks like


all the source code is manage by this src folder. Lets look at how the go lang source's src $GOROOT folder looks like

$GOROOT/src folder structure
Simply it shows the folders that contains particular package's source code.  for a example when we need the fmt API we access this $GOROOT/src path of fmt package and it's publicly exposed source.

So always the $GOROOT contains all the core packages. Ok then what about other packages. I mean 3rd party packages. Check this awesome go site

3rd party library import format of golang

What if you have a 3rd party dependency from github.com. There can be other 3rd part libraries from gitlab.comsourcegraph.comgolang.orggopkg.in, etc... 
  1. How the go try to find those dependency ? 
  2. If not where and how go try to install those dependency ?
First it looks inside the $GOROOT/src (C:\Go\src)if that particular dependency is not there it goes to $GOPATH/src (C:\Users\User\go-projects\src) and looks weather it can finds it.

Once you make the > go get command it will install the dependencies to the $GOPATH/src folder.

So It's always a good practice to maintan your all go project paths inside the $GOPATH. create a root go-projects folder and make that folder path to $GOPATH. then you can manage your and other 3rd party project clearly. If you got any issues retaliated go dependency you know where to look at. 

In this structure whenever you build your project or 3rd party project binary will goes to $GOPATH/bin pkg files related to src goes to $GOPATH/pkg

Basic golang src project structure 
This is how a github projects lives inside the $GOPATH. So keep your and 3rd party projects in one place. Use $GOPATH wisely. 
Note you can have multiple $GOPATH

Ubuntu: export GOPATH=path1:path2:path3...
Windows set    GOPATH=path1;path2;path3

But I prefer 1 $GOPATH just one path to avoid the complexity. 

Hope you guys understood #HappyCoding :)