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

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.

主站蜘蛛池模板: 女性| 沁阳市| 嘉鱼县| 乐山市| 临洮县| 子长县| 西宁市| 比如县| 丹寨县| 景德镇市| 滨州市| 陵川县| 红原县| 翁牛特旗| 扶绥县| 桃江县| 大足县| 扬州市| 四会市| 宜君县| 平阴县| 定日县| 莫力| 台江县| 喀什市| 博乐市| 平原县| 琼结县| 油尖旺区| 南开区| 龙泉市| 崇州市| 临海市| 松江区| 平阴县| 辉县市| 新巴尔虎左旗| 七台河市| 大埔县| 阿坝| 保山市|