Go dependency management introduction
As far as I know, we usually have three ways to manage dependencies for a Go project.
Manually management
To manage dependencies manually, we add all our external dependencies into vendor folder, then add vendor folder into version control system. That’s all!
Dep
The typical usage of dep is that, we write our code first, and then issue dep ensure to scan our code to find out external dependencies. Then dep can download those dependencies and store them inside our project’s vendor folder. Dep will maintain a Gopkg.lock file to store version information. As programmer we don’t edit Gopkg.lock directly, we edit a file named Gopkg.toml to specify rules which will guide dep to generate Gopkg.lock. By using dep, we usually no need to add the vendor folder into version control system, instead we manage Gopkg.lock and Gopkg.toml.
Go module
By using dep or managing manually, we need to put our project properly inside $GOPATH/src if our project contains more than one packages. That’s very unpleasant for some people. So we can use Go module . For a project using Go module, we should have two files: go.mod, go.sum which should be generated via go mod init for a new project.
Inside go.mod we can specify our module’s identity which will be used as a mapping to $GOPATH/src. For example, one of my project has module github.com/dlee/admin, then once I invoke env GO111MODULE=on go build the go tool will treat my project root path as $GOPATH/src/github.com/dlee/admin. Then I can import packages defined inside my project properly. e.g. import "github.com/dlee/admin/pkg1" will cause go build tool search pkg1 from my project folder not $GOPATH/src/github.com/dlee/admin/pkg1.
During daily developing, we use env GO111MODULE=on go get to download/add dependencies or upgrade dependencies, this will trigger updating the go.mod file. Or if needed we can directly edit go.mod. So basically if we clone a Go module enabled project, we can use go mod download to download dependencies, and then we can build the project. To upgrade a dependency, we use env GO111MODULE=on go get foo@version to upgrade to a specific version or env GO111MODULE=on go get foo to upgrade to latest version. Once upgrade, the go.mod and go.sum will be updated automatically.