官术网_书友最值得收藏!

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.

For go get, use the  -u flag to install the updated dependencies of the external package, and -v to see the verbose details of the installation.

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.

主站蜘蛛池模板: 晋中市| 武宣县| 苍山县| 确山县| 麦盖提县| 商都县| 牟定县| 博爱县| 遵义市| 阿克陶县| 香港 | 婺源县| 睢宁县| 山丹县| 宜兰县| 疏勒县| 伊春市| 正镶白旗| 建阳市| 惠安县| 新昌县| 时尚| 黄平县| 纳雍县| 许昌市| 井冈山市| 铁力市| 宜兰市| 崇左市| 丰台区| 德江县| 盘山县| 合江县| 霍山县| 临西县| 鄄城县| 沙湾县| 京山县| 伊金霍洛旗| 昌江| 通河县|