Definition
A module is a collection of related go packages. Modules are the unit of source code interchange and versionning.
Quick history
go getvgogo mod
Terminology
This article refers to recurrent expressions. Let’s clarify them:
go.modgo
Module structure
A module is a tree of Go source files to which is added a file named go.mod. It contains the module import name, and the declaration of dependency requirements, exclusions and replacements. Its content would look like this:
Note that a dependency not directly imported in the module’s source code by an import statement is indentified as indirect in the file.
A module can contain other modules, in which case their content is excluded from the parent module.
go.sum
A module root can reside anywhere on the filesystem, whatever is the current GOPATH.
Module dependencies
GOPATH/src/mod
What does this new structure looks like? Suppose we are working on a module that depends on github.com/me/lib at version 1.0.0. For such a case, in GOPATH/src/mod we would find:
What we can observe is:
@version
Enabling Go modules support
GO111MODULEonoffauto
If set to “on”, module support is enabled whatever path we are in.
If set to “off”, it is permanently disabled.
If unset or set to “auto”, module support is enabled outside of GOPATH only if the current directory is a module root or one of its subdirectories.
Integration
go buildgo installgo rungo test
Autoformat
go mod -fmtgo fmtgo mod -fix
- Rewriting non-canonical version identifiers to semantic versioning form.
- Removing duplicates.
- Updating requirements to reflect exclusions.
Initialization
To create go.mod:
-module
depglideglockgodep
Synchronization
In order to clean up unused dependencies or to fetch new ones, use the sync option:
Adding, excluding and replacing dependencies
Two possibilities: either edit go.mod by hand or use the CLI. The latter comes with the following commands:
Dependency graph
To print the graph of module dependencies:
Generating vendor
If for backward compatibility reasons you need to ship your application with vendoring, you can generate the vendor directory from go.mod thanks to:
Getting help
go help modgo help modules
Golang语言社区
ID:Golangweb