1. Go’s Package Management Mechanisms
1.1 GOPATH
GOPATH pulls code with the go get command and places it in the GOPATH directory.
The problems with GOPATH are:
- It cannot manage package versions
- It uses a global repository, so it cannot isolate projects effectively
1.2 Vendor
Starting with version 1.5, Go added the Vendor mechanism. Vendor solved some of GOPATH’s problems.
The Vendor mechanism manages dependency packages by adding a vendor folder under the project directory.
The problems with Vendor are:
- It cannot resolve nested dependencies
- vendor is only valid under a GOPATH path
1.3 Go modules
Go modules allows project code to live in any directory, with dependency packages stored uniformly under $GOPATH/pkg/mod, avoiding the duplicated code of the vendor approach.
2. Features of Go modules
Go controls whether the Go modules feature is enabled through the GO111MODULE switch variable, which has three possible values: auto/on/off. It was introduced in version 1.11, with a default of auto, and enabled by default in version 1.13.
auto means that the feature is enabled when there is a go.mod in the current directory. In auto mode:
- When compiling inside a GOPATH directory, vendor and GOPATH are used for package management by default
- When compiling outside a GOPATH directory, the settings in go.mod are used for package management by default.
While using Go modules, two files are generated automatically: go.sum and go.mod. Usually both files are also committed to the code repository.
- go.mod
go.mod records the version information and operation commands for dependency packages. go.mod provides four commands: module, require, replace, and exclude.
| |
- go.sum
go.sum provides version checksums.
| |
3. Configuring a Proxy
When installing Go dependency packages, data is requested from the public internet. Some packages are hosted on github.com, and others are hosted in repositories such as golang.org and k8s.gcr.io. Since Google-related URLs are blocked, you often run into network access problems.
Version 1.11 added a new environment variable, GOPROXY, which can be used to configure a mirror proxy for code repositories.
Taking the configuration of jfrog’s GoCenter as an example, run the following in the runtime environment:
| |
That is all it takes to use the proxy provided by jfrog. In addition, GoCenter also offers a package search feature.
Of course, aliyun also provides a GOPROXY:
| |
4. Basic Go modules Commands
The Go modules help documentation already describes this in great detail.
| |
- Create a new directory hello, and add a file hello.go inside it
| |
- Initialize the package with the repository address
| |
- Compile and produce an executable file
| |
- Archive the dependency packages into the project’s vendor directory
| |
- Verify the dependencies
| |
- Check the final directory structure
| |
