- Hands-On RESTful Web Services with Go
- Naren Yellavula
- 426字
- 2021-06-24 17:04:24
Demystifying GOPATH
GOPATH is nothing but the current appointed workspace on your machine. It is an environment variable that tells the Go compiler where your source code, binaries, and packages are placed.
The programmers coming from a Python background may be familiar with the Virtualenv tool for creating multiple projects (with different Python interpreter versions) at the same time. But at a given time, you can activate the environment for the project that you wish to work on and develop your project. Similarly, you can have any number of Go projects on your machine. While developing, set the GOPATH to one of your projects. The Go compiler now activates that project.
It is a common practice to create a project under the home directory and set the GOPATH environment variable as follows:
mkdir /home/user/workspace
export GOPATH=/home/user/workspace
Now, we install external packages like this:
go get -u -v github.com/gorilla/mux
Go copies a project called mux from GitHub into the currently activated project workspace.
A typical Go project, hello, should reside in the src directory in GOPATH, as mentioned on the official Go website:
Let's understand this structure before digging further:
- bin: Stores the binary of our project; a shippable binary that can be run directly
- pkg: Contains the package objects; a compiled program that supplies package methods
- src: The place for your project source code, tests, and user packages
In Go, all the packages imported into the main program have an identical structure, github.com/user/project. But who creates all these directories? Should the developer do that? Yes. It is the developer's responsibility to create directories for their project. It means they only create the src/github.com/user/hello directory.
When a developer runs the install command, the bin and package directories are created if they did not exist before. .bin consists of the binary of our project source code and .pkg consists of all internal and external packages we use in our Go programs:
go install github.com/user/project
Let's build a small service to brush up on our Go language skills. Operating systems such as Debian and Ubuntu host their release images on multiple FTP servers. These are called mirrors. Mirrors are helpful in serving an OS image from the closest point to a client. Let's build a service that finds the fastest mirror from a list of mirrors.