I'm new to Golang. As I understand, when you want to create a new Go project, we just need to create a directory. Then we point the environment variable GOPATH
to this directory. Inside this directory, we create three subdirectories pkg
, src
and bin
. Then when we execute go get ...
, the third-party package will be installed in the pkg
subdirectory. Later if I want to create another Go project, I create a new dir called project2 and point GOPATH
to project2. At this time go get ...
will download third-party package in the pkg
subdirectory of project2. My question is, whether Go has a central repository? If not, the same package will be downloaded twice if they are used in two different projects. Is that true?
There is no central repository of go packages. Go always is looking for packages either in GOPATH or GOROOT. go get simply downloads packages using git or mercurial. I recommend you to read https://golang.org/doc/code.html and https://peter.bourgon.org/go-best-practices-2016/#repository-structure
GOPATH simply tells go compiler where to search for src
, pkg
directories.
Later if I want to create another Go project, I create a new dir called project2 and point GOPATH to project2 … My question is, whether Go has a central repository? If not, the same package will be downloaded twice if they are used in two different projects. Is that true?
No, there is no central repository for Go code. However, it is also not true that the packages will always be downloaded twice.
The misconception here is that GOPATH
points to an individual project: it does not. Instead, GOPATH
points to an environment where all of your packages live; it is where go get
will download packages, and where go build
will look for packages when building.
Instead of changing GOPATH
for every project, you should set GOPATH
once and put all of your projects in $GOPATH/src/
(your projects don't contain an src/
directory, they go in the src/
directory).
So for example, the entire tree might look like:
$GOPATH/src/bitbucket.org/ (or GitHub, or your website, or whatever)
├── YourProject
└── AnotherProject
I guess now there is https://gocenter.jfrog.com/ More info in this blog https://jfrog.com/blog/go-at-full-speed-with-gocenter