SoFunction
Updated on 2025-03-05

Detailed explanation of the introduction and use of Go module

Go1.1.1The version has been released (released on 2018-08-24) a few days ago. From the official blog, I saw that there are two more prominent features, one is what I talked about today.module, module concept. The function is still in the experimental stage and some places still need to be continuously improved. This support is intended to be revised continuously before the official announcement. You can remove the rightGOPATHandgo getCommand support.
If you want to try this new feature nowmodule, you need to put your code repository intoGOPATH/srcOutside the directory. Then create a directoryFile, run from the file treegoOrder.

Introduction to the main concepts

moduleIt's a relatedGoA collection of packages, which are the unit of source code replacement and version control. The module is formed from the source fileThe root directory definition of the file, includingThe directory of a file is also called the module root.moudlesReplace the old basedGOPATHMethod to specify which source files or import packages are used in the project. The module path is the path prefix for importing the package.The file defines the module path and lists the specific versions used during the project build process.

document

File definitionmodulePaths and list other needs inbuildwhen introduced a specific version of the module. For example, in the following example,statement/mWhen the pathmoduleThe root directory ofmoduleDepend on a specific version/x/textand/yaml.v2

module /m

require (
  /x/text v0.3.0
  /yaml.v2 v2.1.0
)

The file can also specify the version to replace and exclude, and the command line will automatically followFile to maintain the version in the requirement statement. If you want to get more informationIntroducing the file, you can use commandsgo help
For files//Comments, not/**/. Each line of the file has an instruction, consisting of an action plus a parameter. For example:

module my/thing
require other/thing 	v1.0.2
require new/thing 		v2.3.4
exclude old/thing 		v1.2.3
replace bad/thing 		v1.4.5 	=> good/thing v1.4.5

The above three verbsrequireexcludereplaceIt indicates: the dependency packages and versions required by the project, excluding special versions of certain packages, and replacing some dependency packages in the current project.
Commands with the same action can be placed in a structure composed of verb + parentheses, for example:

require (
  new/thing v2.3.4
  old/thing v1.2.3
)

Support for other commands

Old version, build compile commandgo buildThere are no parameters in-modParameters, the latest version now has this one, used to matchFile update or other usage control. Form:go build -mod [mode], where mode has the following values:readonlyreleasevendor. When executedgo build -mod=vendorWhen generating the executable file, the project's dependency package will be placed in the main modulevendounder the r directory.
go get -m [packages]The downloaded dependency package will be placed inGOPATH/pkg/modIn the directory, and write dependencies todocument.go get -u=patchAll dependencies under the main module will be updated.
If you encounter an unfamiliar import package, you can look for any module that contains the import package.goThe latest version of the module will be automatically added to thein the file. At the same time, missing modules will be added and useless ones will be deleted.module. For example:go build, go testorgo listOrder. In addition, there is a special commandgo mod tidy, used to view and add missingmoduleRequirement statement and removal of unnecessary.
The file is readable and editable.goThe command line will be updated automaticallyFile to maintain a standard format and precise introduction statement.

Go mod command

Go modProvides a series of operationsmodulesThe command, remember, allgoThe command is now built inmodulesupport, not justgo modOrder. For examplego getWhen , the dependency package version will be automatically added, removed, upgraded, and downgraded in the background.
Command syntax:go mod <command> [arguments]Go modThe following commands are provided, which provide detailed descriptions of more commonly used commands.

download        //Download the module to the local cache. You can view it through the command go env, where the environment variable GOCACHE is the cache address. If the content of the folder is too large, you can use the command go clean -cacheedit          //Edit files from tools or scriptsgraph          //Print module requirements mapinit          //Initialize new module in the current directorytidy          //Add missing modules and remove useless modulesverify         //Verify whether the dependencies have achieved the expected purposewhy           //Explain why packages or modules are needed

go mod download
usage:go mod download [-dir] [-json] [modules]. Use this command to download the specified module. The format of the module can be based on the main module dependency form orpath@versionForm specified. If no parameters are specified, this command will download all dependencies in the main module.
go mod downloadThe command is very useful, mainly used to pre-fille local cache or calculateGoModule Agent's answer. By default, download errors will be output to standard output, and under normal circumstances there is no output.-jsonThe parameters willJSONPrint the downloaded module object in the format, corresponding toGoThis is the object structure.

type Module struct {
  Path    string   //module path
  Version   string   //module version
  Error    string   //error loading module
  Info    string   //absolute path to cached .info file
  GoMod    string   //absolute path to cached .mod file
  Zip     string   //absolute path to cached .zip file
  Dir     string   //absolute path to cached source root directory
  Sum     string   //checksum for path, version (as in )
  GoModSum  string   //checksum for  (as in )
}

go mod init
usage:go mod init [module]. This command initializes and creates a new one in the current directory.You can also create a file manuallyfile, then include somemoduleDeclare, this is more troublesome.go mod initCommands can help us create automatically, for example:

go mod init /m

When using this command,The file must not exist in advance. Initialization will infer the path of the module based on the introduction of the package declaration or if there are already some dependency on the package management tool in your project, for examplegodepglideordep. Sogo mod initIt will also be inferred based on the dependency package management configuration file.
go mod tidy
By default, Go will not be removedUseless dependencies in the file. So when some of your dependencies are not available, you can use itgo mod tidycommand to clear it.
usage:go mod tidy [-v]It adds missing modules and removes unwanted modules. It will be generated after executionFile (module download entry). Add parameters-v,For examplego mod tidy -vThe executed information, i.e. the removed module, can be printed to standard output.
go mod vendor
usage:go mod vendor [-v], this command willbuildAll dependencies required in the stage are placed in the main modulevendorIn the directory and test the packages for all main modules. Similarlygo mod vendor -vWill be added tovendorThe modules in it are printed to standard output.
go mod verify
usage:go mod verify. This command checks whether the current module's dependency has been stored in the local downloaded source code cache, and checks whether there have been any modifications since the download. If all modules are not modified, then it will be printedall modules verified, otherwise the changed content will be printed.

Virtual version number

File and go commands usually use semantic versions as standard form to describe module versions, so that the order of different versions can be compared. For example, the version of the module is v1.2.3, then the virtual version of this version is obtained by re-labeling the version number. Form:v0.0.0-yyyymmddhhmmss-abcdefabcdef. Where time is the UTC time at the time of commit, and the last suffix is ​​the hash prefix of the commit. The time section ensures that the two virtual version numbers can be compared to determine the order of the two.
There are three forms of virtual version numbers below:

  • vX.0.0-yyyymmddhhmmss-abcdefabcdef, this situation is suitable for use before the target version is submitted, without earlier versions. (This form was originally the only form, so some old files use this form)
  • -pre.-abcdefabcdef, this situation is used when the latest version commit before the target version is-pre
  • .(Z+1)--abcdefabcdef, Similarly, this situation is when the target version is submitted before the latest version is

You do not need to manually generate a virtual version. The go command will automatically convert the received commit hash value into the virtual version number.

Environment variables—GO111MODULE

Go 1.11ofmoduleSupport temporary environment variables—GO111MODULE, it can set the following three values:off,onorauto(default).

  1. ifGO111MODULE=off,SogoThe new command line will not be usedmoduleFunction, instead, it will bevendorIn the directory andGOPATHLook for dependency packages in the directory. This model is also calledGOPATH mode
  2. ifGO111MODULE=on,SogoThe command line will use itmodulesFunctions without accessGOPATH. This model is also calledmodule-awaremode, in this mode,GOPATHNo longer herebuild, but despite this, it still assumes the role of storing and downloading dependencies. It will put the dependency package inGOPATH/pkg/modIn the directory.
  3. ifGO111MODULE=auto, this mode is the default mode, which means that if you don't set it, it isauto. In this case,goThe command line will decide whether to enable it based on the current directory.moduleFunction. Only when the current directory isGOPATH/srcOutside the directory and the current directory containsThe file or its subdirectory containsThe file will be enabled.

Specific steps for use:

  • First, update your version to the latest Go version (>=1.11). You can use Baidu to update the version on your own.
  • Through the go command line, enter your current project directory and set temporary environment variables on the command lineset GO111MODULE=on
  • Execute the commandgo mod initGenerate aFile, when executing this command, the current directory cannot existdocument.
  • If it has been generated before, you need to delete it first; if there are some packages in your project that cannot be determined, then the generatedThe file may be incomplete, so continue to execute the following command;
  • implementgo mod tidycommand, it adds missing modules and removes unwanted modules
  • It will be generated after executionFile (module download entry). Add parameters-v,For examplego mod tidy -vThe executed information, i.e. deleted and added packages, can be printed to the command line;
  • Execute the commandgo mod verifyCheck whether all the dependencies of the current module have been downloaded and whether they have been modified after downloading. If all modules have not been modified, then after executing this command, it will printall modules verified
  • Execute the commandgo mod vendorGenerate vendor folder, which will be placed in this folderThe file description dependency package, there is also a file in the folder, it is all modules of your entire project. Before executing this command, if you have a vendor directory before the project, you should delete it first. Similarlygo mod vendor -vThe module added to the vendor will be printed out;

Summarize

This is the article about the introduction and use of Go modules. For more information about using Go modules, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!