Go document: go command

Time:2020-10-28

This paper is updated on April 8, 2020.

Translated from the official document of command go( https://golang.org/cmd/go/ It can be used in China https://golang.google.cn/cmd/go/ )The structure of chapters and paragraphs is slightly changed, and the corresponding go version is 1.14.

catalog
  • go
  • Go bug — start bug report
  • Go build — compile package and its dependent package
  • Go clean — delete object files and cache files
  • Go doc — view documents for packages or symbols
  • Go env — print environment variable
  • Go fix — update package code with new API
  • Go FMT — gofmt (reformat) package code
  • Go generate — generate go files by executing source code
  • Go get — add the dependency package to the current module and install it
  • Go help — view help information
  • Go install — compile and install modules and their dependencies
  • Go list — lists packages and modules
  • Go mod — module maintenance
    • Go mod download — download the module to the local cache
    • Go mod edit — edit with tools or scripts go.mod
    • Go mod graph — print module dependency graph
    • Go mod init — initializes a new module in the current directory
    • Go mod tidy — add missing modules and remove unused ones
    • Go mod vendor — generate dependent vendor copies
    • Go mod verify — validation dependency has expected content
    • Go mod why — explains why the package or module is needed
  • Go run — compile and run go programs
  • Go test — test package
  • Go tool — runs the specified go tool
  • Go version — print go version
  • Go vet — report possible errors in the package
  • Build mode theme — build mode
  • C topic — call between go and C
  • Cache topic — building and testing caches
  • Environment topic — environment variables
  • Filetype theme — file types
  • go.mod Theme—— go.mod file
  • Gopath topic — gopath environment variable
    • Gopath and modules
    • Internal directory
    • Vendor directory
  • The theme of gopath get — the legacy go get of gopath
  • Goproxy topic — module proxy protocol
  • Import path topic — import path syntax
    • Relative import path
    • Remote import path
    • Import path check
  • Modules topics – modules, module versions, and more
    • Module support
    • Defining modules
    • Main module and build list
    • Maintenance module dependency requirements
    • Pseudo version
    • Module query
    • Module compatibility and semantic version control
    • Module code layout
    • Module download and verification
    • Module and using vendor
  • Get module — get module
  • Module auth theme — using go.sum Module verification of
    • Module verification failed
  • Module private topic — module configuration of non public modules
  • Packages topic — package list and schema
  • TestFlag theme — test flag
  • Testfunc topic — test function

go

go  [arguments]

Go is a tool for managing go source code.

Command can be the following commands:

  • Bug: start bug report.
  • Build: compiles the package and its dependent packages.
  • Clean: delete object files and cache files.
  • Doc: view documents for packages or symbols.
  • Env: print environment variables.
  • Fix: update the package code with the new API.
  • FMT: gofmt (reformat) package code.
  • Generate: generate the go file by executing the source code.
  • Get: add the dependency package to the current module and install it.
  • Help: view help information.
  • Install: compile and install the module and its dependencies.
  • List: lists packages and modules.
  • Mod: module maintenance.
  • Run: compile and run the Go program.
  • Test: test package.
  • Tool: run the specified go tool.
  • Version: print the go version.
  • Vet: report possible errors in the package.

Go bug — start bug report

go bug

Open the default browser and launch a new bug report that includes useful system information.

Go build — compile package and its dependent package

go build [-o output] [-i] [build flags] [packages]

Compiles the package with the specified import path and its dependent packages, but does not install the results.

If you build a list of. Go files in a single directory, they are treated as a list of source files that specify a single package.

When compiling packages, ignore the_ test.go ”End of the file.

When compiling a single main package, the generated executable is written to the first source file (e.g., “go build ed.go rx.go ”Write “Ed” or“ ed.exe ”)Or source code directory name (for example: “go build UNIX / Sam” write “Sam” or“ sam.exe ”)Named output file. When writing to an executable file under windows, the suffix “. Exe” is added.

When compiling multiple packages or a single non main package, build compiles the package but discards the target object file. The behavior is only used to check whether the package can be built.

Logo:

  • -i: Also install the dependent packages for the target.
  • -O output: forces the resulting executable or object file to be written to the output file or directory with the specified name, rather than the default behavior described in the last two paragraphs of this section. If the specified name is an existing directory, all result executables are written to that directory.

Build flags are shared by build, clean, get, install, list, run, and test commands

  • -a: Force rebuild is already the latest package.
  • -Asmflags’ [pattern) = Arg list ‘: parameter passed to each go tool ASM call.
  • -Buildmode mode: the build mode used. For more information, see “go help Buildmode”.
  • -Compiler Name: the compiler name used, i.e runtime.Complier (gccgo or GC).
  • -Gcgoflags’ [pattern) = Arg list ‘: parameter passed to each gccgo compiler / linker call.
  • -Gcflags’ [pattern) = Arg list ‘: parameter passed to each go tool comp call.
  • -Installsuffix suffix: suffix used in the package installation directory name to separate the output file from the default build. If the – race flag is used, the installation suffix is automatically set to race or appended if it is explicitly set_ race。 Same for MSAN. A similar effect is achieved with the – Buildmode option, which requires a non default compile flag.
  • -Ldflags’ [pattern) = Arg list ‘: the parameter passed to each go tool link call.
  • -Linkshared: linked to a shared library previously built with – Buildmode = shared.
  • -Mod mode: the module download mode used: readonly, vendor or mod. For more information, see “go help modules.”.
  • -Modcacherw: make newly created directories that are kept in the module cache readable and writable, instead of making them read-only.
  • -Modfile file: in module aware mode, read (and possibly write) standby go.mod File, not in the module root directory go.mod Documents. The name is“ go.mod ”The file must still exist to determine the module root, but it will not be accessed. When – modfile is specified, alternate go.sum The file is also used: its path is generated from the – modfile flag by removing the “. Mod” extension and appending “. Sum”.
  • -MSAN: enables interoperability with memory cleaner, only supports Linux / AMD64, Linux / arm64, and can only use clang / llvm as host C compiler. On Linux / arm64, pie build mode will be used.
  • -n: Prints the actual command to be executed, but does not run.
  • -P n: the number of programs that can run in parallel, such as build commands or test binaries. The default is the number of CPUs available.
  • -Pkgdir dir: install and load all packages (PKG) from dir instead of the usual location. For example, when building with nonstandard settings, use – pkgdir to have packages generated in a specific directory.
  • -Race: enable data race detection, only support Linux / AMD64, FreeBSD / AMD64, Darwin / AMD64, windows / AMD64, Linux / ppc64le, Linux / arm64 (only for 48 bit VMA).
  • -Tags, tag, list: the construction tags to be satisfied during the construction, which is a comma separated list. For build tags, refer to the description of build constraints in the go / build package documentation. (the use of white space delimited lists in earlier go versions has been abandoned, but is still recognized.)
  • -Toolexec ‘CMD args’: a program used to call tool chain programs such as vet and ASM. For example, use the go command to run “CMD args / path / to / ASM” instead of ASM.
  • -Trimpath: removes all file system paths from the target executable. As an alternative to the absolute path of the file system, the recorded file name will start with “go” (for standard libraries), or “module path @ version” (when using modules), or “import path” (when using gopath).
  • -v: Print the compiled package name.
  • -Work: print the temporary working directory and do not delete it when you exit.
  • -x: Print the actual command to be executed and run it.

-Asmflags, – gcgoflags, – gcflags, – ldflags accept a blank separated list of parameters to pass to the underlying tools at build time. To embed white space in a list element, use single or double quotation marks. The parameter list can be preceded by a package pattern and an equal sign, which limits the use of the parameter list to packages that match the pattern (see “go help packages” for a description of package patterns). If there is no schema, the parameter list applies only to packages named on the command line. These flags can be specified repeatedly with different patterns to specify different parameters for different packages. If a package matches the pattern given in more than one flag, the last specified is used. For example, “go build – gcflags = – s FMT” prints only the disassembly of FMT packages, “go build – gcflags = all = – s FMT” prints the disassembly of FMT packages and all their dependent packages.

For more information about specifying packages, see “go help packages.”. For more information about where packages and binaries are installed, see “go help gopath.”. For more information on calls between go and C / C + +, see “go help C”.

Note: the build follows certain conventions, such as those described in “go help gopath.”. However, not all projects comply with these conventions. Using your own conventions to install, or using a separate software to build the system, you can choose to use low-level calls, such as “go tool compile” and “go tool link”, to avoid the overhead of building tools and design decisions.

See: go install, go get, go clean.

Go clean — delete object files and cache files

go clean [clean flags] [build flags] [packages]

Remove the object file from the package source directory. The go command builds most of the object files in the temporary directory, so go clean is mainly concerned with the object files left over by other tools or by manually calling go build.

If you give the packages parameter or the – I or – R flag, clean removes the following files from each source file directory corresponding to the import path:

  • A kind of Obj /: old object file directory, from makefile.
  • A kind of Test /: old test file directory, from makefile.
  • A kind of testmain.go : old gotest file, from makefile.
  • test.out : old test log, from makefile.
  • build.out : old test log, from makefile.
  • *. [568ao]: object file, from makefile.
  • Dir (. Exe): from go build.
  • DIR.test (. Exe): from go test – C.
  • Mainfile (. Exe): from go build MAINFILE.go 。
  • *. so: from swig.

In the above list, dir represents the last element of the directory path, and mainfile represents the base name of any go source file in the directory that was not included when the package was built.

Logo:

  • -Cache: delete the entire go build cache.
  • -i: Delete the relevant installed archive or binary (created by “go install”).
  • -Modcache: delete the entire module download cache, including the decompressed source code depending on the specified version.
  • -n: Prints the actual command to be executed, but does not run.
  • -r: Recursively applies to all dependent packages specified by the import path.
  • -Testcache: expiration of all test results in go build cache.
  • -x: Print the actual command to be executed and run it.

For more information about build flags, see “go help build.”.

For more information about specifying packages, see “go help packages.”.

Go doc — view documents for packages or symbols

go doc [-u] [-c] [package|[package.]symbol[.methodOrField]]

Prints a document comment about the item specified by the parameters (package, constant, function, type, variable, method, struct field), followed by a line summary of each first level item under the item (the item is a package level declaration, a type is its method, and so on).

The doc command takes 0, 1, or 2 parameters.

If 0 parameters are used, it will run:

go doc

The package document of the package in the current directory will be printed. If the package is a command package (main package), the export symbol of the package is omitted from the display output, unless the – CMD flag is specified.

When run with a parameter, the parameter is treated as a go syntax representation of the item to present the document. The entry specified by the parameter depends on what is installed in goroot and gopath, as well as the format of the parameter. The format of the parameter is as follows:

go doc 
go doc [.]
go doc [.][.]
go doc [.][.]

The first item in the list above that matches the parameters is the item of the document to be printed. (see the example below.) However, if the parameter starts with an uppercase letter, it is assumed that it represents a symbol or method in the current directory.

For packages, the scanning order is determined lexically by breadth first. That is, the presented package is one of the matching searches, and is the first lexically searched in its hierarchy closest to the search root. Goroot trees are always fully scanned before gopath.

If no packages are specified or matched, packages in the current directory are selected, so “go doc foo” displays documents with the symbol foo in the current directory.

The package path must be a qualified path or the correct suffix of the path. The usual package mechanism of go tools is not applicable to package path elements like “.” and “…” that are not implemented by go doc.

When running with two parameters, the first parameter must be a complete package path (not just a suffix), and the second parameter is a symbol, a symbolic method, or a structure field of a symbol. This is similar to the syntax accepted by godoc:

go doc  [.]

In all forms, when matching symbols, the lowercase letters of the parameter are not case sensitive, but uppercase letters match only uppercase. This means that if different symbols have different case, there may be multiple matches for the lower case parameter in the package. If this happens, documents for all matches are printed.

Example:

  • Go doc: displays the document for the current package.
  • Go doc foo: displays the document of foo in the current package. (foo starts with an uppercase letter, so it cannot match as a package path.)
  • Go doc encoding / JSON: displays the document of encoding / JSON package.
  • Go doc JSON: short for encoding / JSON.
  • go doc json.Number (or go doc json.number ): display json.Number Document and method summary.
  • go doc json.Number.Int64 (or go doc json.number.int64 ): display json.Number The document for the Int64 method of.
  • Go doc CMD / doc: displays the package document of DOC command.
  • Go doc – CMD CMD / doc: displays package documents and export symbols for DOC commands.
  • go doc template.new : displays the document for the new function of HTML / template. (HTML / template lexically precedes text / template.)
  • go doc text/ template.new (one parameter): displays the document for the new function of text / template.
  • Go doc text / template NEW (two parameters): displays the document for the new function of text / template.

At least in the current package tree structure, the following calls are printed json.Decoder Document of decode method of:

  • go doc json.Decoder.Decode
  • go doc json.decoder.decode
  • go doc json.decode
  • cd go/src/encoding/json; go doc decode

Logo:

  • -All: displays all documents for the package.
  • -c: The time zone of the matching symbol is case sensitive.
  • -CMD: treat the command (main package) as a normal package. Otherwise, when the top-level document of the package is displayed, the export symbol of the main package will be hidden.
  • -Short: one line for each symbol.
  • -SRC: displays the complete source code of the symbol. This displays the complete go code for its declaration and definition, such as function definition (including function body), constant block referenced by type declaration or closure. The output may therefore contain details that are not exported.
  • -u: Display documents of symbols, methods and fields that are not exported just like exported symbols, methods, and fields.

Go env — print environment variable

go env [-json] [-u] [-w] [var ...]

Print go environment variable information.

Env prints information like a shell script (like a batch file in Windows) by default. If one or more variable names are given as parameters, env prints its value on a new line for each variable with the specified name.

Logo:

  • -JSON: print environment variables in JSON format instead of shell scripts.
  • -u: One or more parameters are required. If the environment variable with the specified name has been set with “go env – W”, its default setting will be cancelled.
  • -w: One or more parameters of the format name = value are required to modify the default settings of the environment variable with the specified name using the specified values.

For more information about environment variables, see “go help environment.”.

Go fix — update package code with new API

go fix [packages]

Run the go fix command on the package specified by the import path.

For more information about fix, see “go doc CMD / fix.”. For more information about specifying packages, see “go help packages.”.

To use specific options, run “go tool fix.”.

See: go FMT, go vet.

Go FMT — gofmt (reformat) package code

go fmt [-n] [-x] [packages]

Run the “gofmt – L – W” command on the package specified by the import path. The modified file name will be printed.

For more information about gofmt, see “go doc CMD / gofmt.”. For more information about specifying packages, see “go help packages.”.

Logo:

  • -Mod: the value of the flag sets which module download mode to use: readonly or vendor. For more information, see “go help modules.”.
  • -n: Prints the actual command to be executed, but does not run.
  • -x: Print the actual command to be executed and run it.

To use specific options, run gofmt directly.

See: go fix, go vet.

Go generate — generate go files by executing source code

go generate [-run regexp] [-n] [-v] [-x] [build flags] [file.go... | packages]

The command is executed by the instructions described in the existing file. The command can run any process, but the purpose is to create or update go source files.

Go generate will never run automatically through go build, go get, go test, etc. It must be run explicitly.

Go generate scan file search command. The command is a line in the following format:

//go:generate command argument...

(Note: there is no blank space at the beginning and no blank space in the middle of the “/ / go”) where command is the generator to run, corresponding to the executable file that can be run locally. It must be in a shell path (such as gofmt), be a fully qualified path (such as / usr / you / bin / mytool), or a command alias, as described below.

In order to communicate to humans and machine tools, the code is generated automatically. The generated source code should have a line of regular expression (in go syntax) that matches the following:

^// Code generated .* DO NOT EDIT\.$

The line can appear anywhere in the file, but is usually placed near the beginning to make it easier to find.

Note that go generate does not parse files, so lines that look like instructions in comments or multiline strings are treated as instructions.

The parameters of the instruction are white space separated tokens, which can be strings enclosed by double quotation marks. Each token is passed to the generator as an independent parameter when the generator is running.

Quoted strings use go syntax and are evaluated before execution; a quoted string is used as a separate parameter of the generator.

Go generate sets several environment variables when running the generator:

  • $goarch: Architecture at execution time (arm, AMD64, etc.).
  • $goos: the operating system at the time of execution (Linux, windows, etc.).
  • $gofile: base name of the file.
  • $GOLINE: the line number of the instruction in the source file.
  • $gopackage: the package name of the file containing the directive.
  • Dollar: a dollar sign.

With the exception of variable substitution and quoted string evaluation, special processing such as “globbing” (file name wildcard matching) is not performed on the command line.

As the last step before executing the command, any call to any alphanumeric environment variable, such as $gofile or $home, is expanded on the command line. On all operating systems, the expansion syntax for environment variable names looks like $name. Because of the order in which they are evaluated, environment variables are expanded even in quoted strings. If the environment variable named name is not set $name expands to an empty string.

Instructions in the following form:

//go:generate -command xxx args...

Indicates that, for the continuation part of this source file only, the string XXX represents the command specified by the parameter. This can be used to create aliases or generators that handle multiple words. For example:

//go:generate -command foo go tool foo

Indicates that the command “foo” represents the generator “go tool foo”.

Generate processes packages one at a time in the order given on the command line. If the command line lists. Go files in a separate directory, they are treated as a separate package. In a package, generate processes the source files one at a time in the order of the file names in the package. In a source file, generate runs the generators in the order they appear in the file, one at a time. The go generate tool also sets the build flag “generate” so that files can be reviewed by go generate but ignored at build time.

If any generator returns an error exit status, “go generate” will skip all successive processing of the package.

The generator runs in the source code directory of the package.

Logo:

  • -Run ”: if not null, specifies a regular expression to select the instruction to execute, and the full original source text of the instruction (ignoring white space and newlines at the end) matches the regular expression.

Standard build flags, including – V, – N, and – x, are also accepted.

  • -n: Prints the actual command to be executed, but does not run.
  • -v: Print the package name and file name being processed.
  • -x: Print the actual command to be executed and run it.

For more information about build flags, see “go help build.”.

For more information about specifying packages, see “go help packages.”.

Go get — add the dependency package to the current module and install it

go get [-d] [-t] [-u] [-v] [-insecure] [build flags] [packages]

Get parses and adds dependencies for the currently developed module, then builds and installs the dependencies.

The first step is to resolve which dependencies need to be added.

For each named package or package pattern, get has to decide which version the relevant module uses. By default, get looks for the last tagged release, such as v0.4.5 or v1.2.3. If there is no tagged release, get looks for the last tagged pre release, such as v0.0.1-pre1. If there is no tagged version at all, get looks for the last known commit. If the module is not already dependent and requires a later version (for example, a pre release version that is newer than the last release), get will use the version it finds. Otherwise, get will use the version required by the current dependency.

The default version selection can be overridden by adding the @ version suffix to the package name parameter, such as “go get” golang.org/x/text @V0.3.0 “. Version version can also be a prefix: @ 1 indicates the last available version starting with v1. For the complete query syntax, see “module query” in “go help modules”.

For modules stored in the source control repository, the version version suffix can also be a commit hash, branch identifier, or other syntax known to the source control system, such as “‘Go get.” golang.org/x/text @master”。 Note that branch names that are covered by query syntax of other modules cannot be selected explicitly. For example, the suffix @ V2 represents the last version starting with V2, not a branch named v2.

If the module being parsed is already a dependency of the current development module, get will update the required version of the dependency. Specifies that an earlier version than the version required by the current dependency is valid and demotes the dependency. The version version suffix @ none means that the dependency should be completely removed. Demote or delete the dependent modules on it as needed.

The version version suffix @ latest explicitly requires the release version of the last minor version of the module named with the specified path. The suffix @ upgrade is similar to @ latest, but the module will not be demoted if it is currently dependent on a revision or pre release version that is newer than the last release. The suffix @ patch requires the last patch: the last release that has the same major and minor versions as the version required by the current dependency. Similar to @ upgrade, @ patch does not demote modules when a newer version of the dependency is required. If the module of the specified path has not been required by dependency, @ upgrade and @ patch are equivalent to @ latest.

Although get uses the last version of the module that contains the named package by default, it does not use the last version of the module’s dependent modules. Instead, it prefers to use the specific dependent version that the module requires. For example, if the last version of module a dependency requires v1.2.3 of module B, and v1.2.4 and V1.3.1 of module B are also available, then “go get a” will use the last version of module a, but use v1.2.3 of module B, as required by module a. (if there is a dependency conflict for a specific module, “go get” will resolve the dependency conflict by using the maximum dependency version.)

In general, adding a new dependency may require upgrading the existing dependency to ensure a normal build, and “go get” is done automatically. Similarly, demoting one dependency may require demoting other dependencies, and “go get” is done automatically.

The second step is to download (if necessary), build, and install the package with the specified name.

If the parameter names a module but does not name a package (because there is no go source code in the module’s root directory), the parameter skips the installation step without causing the build to fail. For example, “go get golang.org/x/perf ”It will still succeed even if the import path does not have the relevant code.

Note that the package mode is allowed and will be extended after the module version is parsed. For example, “go get golang.org/x/perf/cmd/ … “to add the last golang.org/x/perf And then install the commands from the last version (under the CMD directory).

If no package name parameter is specified, “go get” is applied to go packages in the current directory, if any. Specifically, “go get – U” and “go get – u = patch” update all dependencies of the package. If there is no package name parameter and no – U flag, “go get” is equivalent to “go install” and “go get – D” is equivalent to “go list”.

Logo:

  • -d: Download the source code needed to build the package with the specified name, including the required dependent source code, but not build and install them.
  • -Execute: allows unsafe schemes such as HTTP to pull and resolve custom domain names from the repository. Use with caution.
  • -t: Also add the modules required for the package build test specified on the command line.
  • -u: At the same time, update the dependency module of the package specified in the command line to use the release version of the latest minor version or the release version of the patch version, provided that these versions are available. Continuing with the previous example, “go get – u a” uses the last version of module a and V1.3.1 of module B (instead of v1.2.3). If module B dependencies require module C, but module C is not a dependency of building module a (excluding tests), then module C will not be updated.
  • -U = patch: (different from – U) the dependent module is also updated, but the difference is that the release version of the patch version is selected by default. Continue with the previous example, “go get – u = patch [email protected] ”The last version of module a and v1.2.4 of module B (instead of v1.2.3) will be used, while “go get – u = patch a” will use the release of the patch version of module a.

When – t and – u are used together, the dependent modules of the modules needed to build the test are also updated.

For more information about modules, see “go help modules.”.

For more information about specifying packages, see “go help packages.”.

The behavior of using modules to manage source code and dependencies was described above. If, on the contrary, the go command runs in gopath mode, the content of “go help get” will be different. Similarly, the flag and behavior details of get will also change. See “go help modules” and “go help gopath get.”.

See: go build, go install, go clean, go mod.

Go help — view help information

go help 
go help

Use “go help””Get about the command (i.egoSection) for more information. Use “go help””Get more information about topics.

Additional help topics are:

  • Build mode: Build mode.
  • c: Call between go and C.
  • Cache: build and test the cache.
  • Environment: environment variable.
  • Filetype: file type.
  • go.mod : go.mod Documents.
  • Gopath: gopath environment variable.
  • Gopath get: go get of legacy gopath.
  • Goproxy: module proxy protocol.
  • Import path: import path syntax.
  • Modules: modules, module versions, and more.
  • Module get: module aware go get.
  • Module auth: Using go.sum Module verification.
  • Module private: module configuration for non-public modules.
  • Packages: package list and schema.
  • TestFlag: test flag.
  • Testfunc: test function.

Go install — compile and install modules and their dependencies

go install [-i] [build flags] [packages]

Compile and install the package specified by the import path.

The executable is installed in the directory specified by the Gobin environment variable, which is $gopath / bin by default or $home / go / bin if the gopath environment variable is not set. The executable in $goroot is installed in $goroot / bin or $gotooldir, not $Gobin.

When module aware mode is disabled, other packages of non executable files will be installed in the directory $gopath / PKG / $goos_ $goarch. When module aware mode is enabled, other packages of non executable files will be built and cached, but will not be installed.

Logo:

  • -i: Also install the dependency of the package with the specified name.

For more information about build flags, see “go help build.”. For more information about specifying packages, see “go help packages.”.

See: go build, go get, go clean.

Go list — lists packages and modules

go list [-f format] [-json] [-m] [list flags] [build flags] [packages]

Lists packages with the specified name, one on a line. The most commonly used flags are – F and – JSON, which control the output print format of each package. Other logos, documentation below, control more specific details.

The default output shows the import path of the package:

bytes
encoding/json
github.com/gorilla/mux
golang.org/x/net/html

Sign (for the description of other signs, refer to – f or – M)

  • -Compiled: set compiled gofiles to go source files submitted to the compiler. Typically, this means that it repeats the files listed by gofiles, and then adds the go code generated by processing cgofiles and swigfiles. The imports list contains the union of all imports from gofiles and compiled gofiles.

  • -DEPs: not just traversing packages with the specified name, but also traversing their dependencies. List traverses them in a depth first postorder traversal, so a package is listed after all its dependencies. Packages that are not explicitly listed on the command line will have a deponly field set to true.

  • -e: Change the handling of error packets, which are either non-existent or incomplete. By default, the list command prints an error message for each error packet into the standard error output, and then ignores them in normal printing. Using the – e flag, the list command will not print error messages to the standard error output, but will process the error packets in a normal printing manner. Error packets will have non empty importpath and non nil error fields; other information may or may not be missing (set to zero).

  • -Export: sets the export field to the file name that contains the latest export information for the specified package.

  • -f: Specifies the alternate format used by the list, using the syntax of the template package. The default output is equivalent to – f ‘{{. Importpath}}’. The structure passed to the template is:

    type Package struct {
    	Dir string // directory containing package source code
    	Importpath string // the import path of the package in the directory
    	Importcomment string // path to import comments in package description
    	Name string // package name
    	Doc string // package document string
    	Target string // installation path
    	Shlib string // the shared library containing this package (only used when setting - linkshared)
    	Goroot boot // is this package in goroot
    	Standard bool // is this package one of the go standard libraries
    	Will stale bool / "go install" handle this package
    	Stalereason string // resolution reason when stale = = true
    	Root string // contains the goroot or gopath directory of the package
    	Conflictdir string // the directory with the same name in $gopath
    	Binaryonly bool // binary package only (no longer supported)
    	Fortest string // the package is only used under the test of the package with the specified name
    	Export string // file containing exported data (when - export is used)
    	Module * module // the module information contained in the package, if any (NIL can be used)
    	Match [] string // matches the command line pattern of this package
    	Deponly bool // if true, the package is only a dependency and is not explicitly listed on the command line
    	
    	//Source file
    	Gofiles [] string //. Go source files (excluding files in cgofiles, testgofiles, xtestgofiles)
    	Cgofiles [] string // import the. Go source file of "C"
    	Compiled gofiles [] string // the. Go file submitted to the compiler (when - compiled is used)
    	Ignoredgofiles [] string // ignored. Go source files due to build restrictions
    	Cfiles [] string //. C source file
    	Cxxfiles [] string /. CC /. Cxx /. CPP source file
    	Mfiles [] string //. M source file
    	Hfiles [] string /. H /. HH /. HPP /. Hxx source file
    	Fortran source file for ffiles [] string /. F /. F /. For /. F90
    	Sfiles [] string //. S source file
    	Swigfiles [] string //. Swig file
    	Swigcxxfiles [] string //. Swigcxx file
    	Sysofiles [] string // add to the archived. Syso object file
    	Testgofiles [] string // in the package_ test.go file
    	Xtestgofiles [] string // out of package_ test.go file
    	
    	//CGO instruction
    	Cgocflags [] string // CGO: flag for C compiler
    	Cgocpflags [] string // CGO: flag for C precompiler
    	Cgoxxflags [] string // CGO: flag for C + + compiler
    	Cgolflags [] string // CGO: flag for FORTRAN compiler
    	Cgoldflags [] string // CGO: flag for linker
    	Cgopkgconfig [] string // CGO: PKG config name
    	
    	//Dependent information
    	Imports [] string // the import path used by this package
    	Importmap map [string] string // the mapping from the original import path to the importpath (the identification entry information is omitted)
    	DEPs [] string // all (recursive) import dependencies
    	Testimports [] string // import dependencies used by testgofiles
    	Xtestimports [] string // import dependencies used by xtestgofiles
    	
    	//Error message
    	Incomplete bool // is there any error in this package or dependent package
    	Error * packageerror // error loading the package
    	Depserrors [] * packageerror // error loading dependent packages
    }

    The importpath reported by packages in the vendor directory includes the path of the vendor directory itself (for example, “D / vendor / P” instead of “P”) so that importpath uniquely identifies a copy of a given package. The import, DEPs, testimports, and xtetimports lists also contain the import path for this extension. For more information about using vendor, see golang.org/s/go15vendor 。

    Error message, if any:

    type PackageError struct {
    	Importstack [] string // the shortest path from the package name specified on the command line to this
    	POS string // wrong location (if any, file name: line number: column number)
    	Err string // error itself
    }

    Module information is a module structure, which is defined in the – M discussion below.

    Template function “join” call strings.Join 。

    The template function “context” returns the construction context, which is defined as follows:

    type Context struct {
    	Goarch string // target architecture
    	Goos string // target operating system
    	GOROOT        string   // GOROOT
    	GOPATH        string   // GOPATH
    	Cgoenabled bool // CGO available
    	Useallfiles bool // whether to use all files, thus ignoring the use of + build to specify the line and file name
    	Compiler string // the compiler assumed when calculating the target path
    	Buildtags [] string // build constraint to match the line specified by + build
    	Releasetags [] string // the release that is compatible with the current release
    	Installsuffix string // suffix used in the name of the installation directory
    }

    For more information about the meaning of these fields, see the go / build package’s context type documentation.

    The file paths in dir, target, shlib, root, conflictdir, and export are absolute paths.

    By default, the names in the gofiles, cgofiles, and other lists are files in the dir directory (that is, the path relative to dir, not the absolute path). When the – composed and – test flags are used, the generated file is the absolute path to the cached copy of the generated go source code. Even if they are go source files, the path may not end with “. Go”.

  • -Find: finds packages with the specified name but does not resolve their dependencies: the imports and DEPs lists will be empty.

  • -JSON: package data is printed in JSON format instead of template package format.

  • -m: List modules instead of packages.

    When listing modules, the – f flag still specifies a format template that applies to the go structure, but is now a module structure:

    type Module struct {
    	Path string // module path
    	Version string // module version
    	Versions [] string // available module versions (when - versions is used)
    	Replace * module // replaced by this module
    	Time      * time.Time    //Version creation time
    	Update * module // available updates, if any (when using - U)
    	Main bool // is the main module?
    	Indirect bool // is the module only indirectly dependent on the primary module?
    	Dir string // the directory where the module saves the files, if any
    	Gomod string // the module go.mod The path to the file, if any
    	Goversion string // the version of go used in the module
    	Error * moduleerror // error loading module
    }
    
    type ModuleError struct {
    	Err string // error itself
    }

    If the module is in the module cache or if the – modfile flag is used, the file that gomod points to may be outside the module directory.

    The default output is the print module path, followed by information about versions and substitutions, if any. For example, “go list – m all” might print:

    my/main/module
    golang.org/x/text v0.3.0 => /tmp/text
    rsc.io/pdf v0.1.1

    The module structure has a string method to format this line of output, so the default format is equivalent to – f ‘{{. String}}’.

    Note that when a module is replaced, its replace field describes the substituted module, and its dir field is set to the directory of the source code of the replacement module, if any. (that is, if replace is not nil, then dir is set to Replace.Dir Cannot access the substituted source code.)

    The parameter list – M is resolved to a list of modules, not packages. The main module is the module that contains the current directory. The active module is the main module and its dependencies. Without parameters, list – M shows the main module. With parameters, list – M displays the module specified by the parameter. Any active module can be specified through its module path. The special pattern “all” specifies all active modules, first the main module, and then the dependencies sorted using the module path. The pattern containing “…” specifies the active module whose module path matches the pattern. [email protected] A query of the form specifies the result of the query, not limited to the active module. For more information about module queries, see “go help modules.”.

    The template function “module” uses a single string parameter, must be a module path or query, and returns the specified module in the form of a module structure. If an error occurs, the result will be a module structure with a non nil error field.

  • -Text: reports not only packages with specified names, but also their test binaries (for packages with tests) to accurately pass the test binaries to the source code analysis tool. Test the import path of the binary report. Add “. Text” suffix to the import path of the package, such as “math”/ rand.test ”。 When building tests, it is sometimes necessary to rebuild some of the test specific dependencies (most commonly the package being tested itself). The import path of the report for the package recompiled for a specific test binary is added with a space and the name of the test binary in parentheses, such as “math / Rand [math/ rand.test ]”Or” regexp “[ sort.test ]”。 Fortest is also set to the name of the package being tested (in the previous example, “math / Rand” or “sort”).

  • -u: Add information about available upgrades. When the last version of a given module is newer than the current module, – U sets the update field of the module to information about the newer module. The string method of the module represents an available upgrade by formatting a newer version in parentheses after the current version. For example, “go list – M – u all” might print:

    my/main/module
    golang.org/x/text v0.3.0 [v0.4.0] => /tmp/text
    rsc.io/pdf v0.1.1 [v0.1.2]

    (for tools, “go list – M – U – JSON all” may be easier to parse.)

  • -Versions: set the versions field of the module to a list of all known versions of the module, and sort them according to the semantic version, from the earliest to the last. This flag also changes the default output format to display the module path, followed by a space separated list of versions.

For more information about build flags, see “go help build.”.

For more information about specifying packages, see “go help packages.”.

For more information about modules, see “go help modules.”.

Go mod — module maintenance

go mod  [arguments]

Command can be the following commands:

  • Download: download the module to the local cache.
  • Edit: edit through tools or scripts go.mod 。
  • Graph: print module dependency diagram.
  • Init: initializes the new module in the current directory.
  • Tidy: add missing modules and remove unused ones.
  • Vendor: generates a copy of the dependent vendor.
  • Verify: the validation dependency has the expected content.
  • Why: explain why the package or module is needed.

Go mod provides access to module operations.

Note that module support is built into all go commands, not just “go mod.”. For example, daily additions, deletions, upgrades, and demotions of dependencies should be done using “go get.”. For an overview of module functions, see “go help modules.”.

For more information about commands, see “go help mod””。

Go mod download — download the module to the local cache

go mod download [-x] [-json] [modules]

Download to download the module with the specified name. You can select the module mode that the main module depends on, or [email protected] Module query in the form of. Without parameters, Download applies to all dependencies of the main module.

The go command will automatically download modules as needed during normal execution. The “go mod download” command is mainly used to pre fill the local cache or calculate the results of go module agents.

By default, download does not write to standard output. It may print progress information and errors to standard error output.

Logo:

  • -JSON: print a series of JSON objects to the standard output, describing each downloaded module (or failure), which is equivalent to the go structure:

    type Module struct {
    	Path string // module path
    	Version string // module version
    	Error string // error in loading module
    	Info string // the absolute path of the cached. Info file
    	Gomod string // absolute path of cached. Mod file
    	// the zip file path of zip
    	Dir string // absolute path of the root directory of the cached source file
    	Sum string // path and version checksums (e.g go.sum As shown in)
    	GoModSum string //  go.mod Check sum (e.g go.sum As shown in)
    }
  • -x: Print the actual command to be executed and run it.

For more information about module queries, see “go help modules.”.

Go mod edit — edit with tools or scripts go.mod

go mod edit [editing flags] [go.mod]

Edit provides an editor go.mod The command line interface is mainly provided for tools or scripts. It reads only go.mod ; does not look for information about modules. By default, edit reads and writes the go.mod File, but you can also specify a different target file after the flag.

Logo:

  • [email protected] : removes exclusions for the given module path and version.

  • -Dropplace = old [@ v]: removes the substitution for the given module path and version. If @ V is omitted, delete the replacement of the module without version.

  • -Drorequire = path: delete the module required by the given module path dependency. This flag is mainly provided for tools to understand the module diagram. Users should use “go get” [email protected] ”, can make other go.mod Adjust as needed to meet the limits imposed by other modules.

  • [email protected] : adds an exclusion for the given module path and version. Note that if the exclusion already exists [email protected] There is no operation.

  • -FMT: reformatting go.mod No other changes will be made. Use or rewrite go.mod Any other modification of the file also means this reformatting. The only time this flag is needed is if no other flag is specified, such as “go mod Edit – FMT”.

  • -Go = version: set the expected version of the go language.

  • -JSON: print the final in JSON format go.mod Instead of writing it back go.mod 。 The JSON output corresponds to these go types:

    type Module struct {
    	Path string
    	Version string
    }
    
    type GoMod struct {
    	Module  Module
    	Go      string
    	Require []Require
    	Exclude []Module
    	Replace []Replace
    }
    
    type Require struct {
    	Path string
    	Version string
    	Indirect bool
    }
    
    type Replace struct {
    	Old Module
    	New Module
    }
  • -Module: modify the module path( go.mod The module line of the file).

  • -Print: print the final in its text format go.mod Instead of writing it back go.mod 。

  • -Replace = old [@ v] = new [@ v]: adds an alternative for a given module path and version pair. If [email protected] If @ V is omitted in the, the replacement of the left module without version is added, which is applicable to all versions of the left module path. If [email protected] The new path should be the local module root directory, not the module path. Note that – replace overlaps any redundant substitutions for old [@ v], so omitting @ V will remove existing substitutes for a particular version.

  • [email protected] : add the module required by the given module path and version dependency. Note that – require overrides any existing modules that depend on the path. This flag is mainly provided for tools to understand the module diagram. Users should use “go get” [email protected] ”, can make other go.mod Adjust as needed to meet the limits imposed by other modules.

-The require, – droprequire, – exclude, – dropexclude, – replace, – dropplace flags can be repeated, and the modifications are applied in the given order.

Pay attention to this description go.mod The file itself does not describe other indirectly referenced modules. For building a complete collection of usable modules, use “go list – M – JSON all.”.

For example, the tool can be obtained as a data structure by parsing the output of “go mod Edit – JSON” go.mod You can then make changes by calling “go mod edit” with – require, – exclude, and so on.

Go mod graph — print module dependency graph

go mod graph

Print the module dependency requirement diagram in text form (substitution applied). Each line of output has two fields separated by spaces: one of the module and its dependency requirements. Each module is marked as [email protected] Except for the main module, it has no @ version suffix.

Go mod init — initializes a new module in the current directory

go mod init [module]

Initialize and write a new go.mod To the current directory is actually to create a new module with the current directory as the root. file go.mod Must not exist. If possible, init guesses the module path from the import annotation (see “go help import path”) or from version control configuration. To override this guess, provide the module path as a parameter.

Go mod tidy — add missing modules and remove unused ones

go mod tidy [-v]

ensure go.mod Consistent with the source code in the module. It adds any missing modules necessary to build the packages and dependencies of the current module, and removes unused modules that do not provide any valuable packages. It also adds any missing entries to the go.mod And delete any unnecessary entries.

Logo:

  • -v: Print the information of the deleted module to standard error output.

Go mod vendor — generate dependent vendor copies

go mod vendor [-v]

Reset the vendor directory of the main module to contain all the packages needed to build and test the packages for all the main modules. Does not include test code for packages in vendor.

  • -v: Print the vendor module and package names to standard error output.

Go mod verify — validation dependency has expected content

go mod verify

Check that the dependencies of the current module stored in the local download source cache have not been modified since the download. If all modules have not been modified, print “all modules verified”. Otherwise, it reports which module has been modified and causes “go mod” to exit in a non-0 state.

Go mod why — explains why the package or module is needed

go mod why [-m] [-vendor] packages...

Logo:

  • -m: By default, why shows the shortest path from the main module to each package listed in the import diagram. Given the – m flag, why treats the parameter as a list of modules and finds out the paths of all packages in each module.
  • -Vendor: by default, why queries the package graph that matches “go list all”, including packages related to testing reachable packages. -The vendor flag causes why to exclude test related packages that depend on packages.

The output is a series of sections, one-to-one corresponding to the name of each package or module in the command line, separated by a blank line. Each section begins with a comment line “# package” or “# module”, giving the target package or module. The following lines give the path through the import diagram, one package and one line. If the package or module is not referenced by the main module, the section displays a separate parenthesized prompt to indicate the fact.

For example:

$ go mod why golang.org/x/text/language golang.org/x/text/encoding
# golang.org/x/text/language
rsc.io/quote
rsc.io/sampler
golang.org/x/text/language

# golang.org/x/text/encoding
(main module does not need package golang.org/x/text/encoding)
$

Go run — compile and run go programs

go run [build flags] [-exec xprog] package [arguments...]

Compile and run the main go package with the specified name. Packages are usually specified as a list of. Go source files in a separate directory, but can also be import paths, file system paths, or patterns that match individual known packages, such as “go run.” or “go run my / CMD.”.

Logo:

  • -Exec: by default, “go run” directly runs the compiled binary: “a.out arguments…”. Given the – exec flag, “go run” uses xprog to call the binary: “xprog a.out arguments…”.

    If the – exec flag is not given, goos or goarch is different from the system default, with a name of go_ $GOOS_ $GOARCH_ The program of exec can be found in the current search directory, “go run” uses this program to call binary files, such as “go”_ nacl_ 386_ exec a.out arguments…”。 This allows cross compiled program execution when emulators or other execution methods are available.

The exit state of run is not the exit state of the compiled binary.

For more information about build flags, see “go help build.”. For more information about specifying packages, see “go help packages.”.

See: go build.

Go test — test package

go test [build/test flags] [packages] [build/test flags & test binary flags]

“Go test” automatically tests the package named after the import path. It prints a summary of the test results in the following format:

ok   archive/tar   0.011s
FAIL archive/zip   0.022s
ok   compress/gzip 0.033s
...

Each failed packet is followed by a detailed output.

“Go test” will match the name with the file pattern “*test.go ”Any files together, recompile each package. These additional files can contain test function, benchmark function and example function. For more information, see “go help testfunc.”. Each package listed causes a separate test binary to be executed. In order to“”(including “_ test.go ”)Files that start with “.” are ignored.

Declaration with Suffix “_ The test file of the “test” package will be compiled into a separate package, and then linked to the test binary of the main package and run.

Go tool will ignore the directory named “testdata” so that it can hold the auxiliary data needed to be tested.

As part of building the test binaries, go test runs go vet on the package and its test source files to find obvious problems. If go vet finds any problems, go test reports them and does not run the test binaries. Use only the highly trusted subset of the default go vet check. The self is: “atomic”, “bool”, “buildtags”, “nilfunc” and “printf”. You can view the documentation for these and other vet tests via “go doc CMD / vet”. To disable running go vet, use the – vet = off flag (seeTestFlag theme — test flagSection).

All test output and summary lines are printed to the standard output of the go command, even if test prints them to its own standard error output. (the standard error output of the go command is reserved for printing the build test errors.)

Go test runs in two different modes:

The first, called the local directory mode, occurs when go test is called without package parameters (for example, “go test” or “go test – V”). In this mode, go test compiles the package source and test files found in the current directory, and then runs the generated test binaries. In this mode, caching (discussed below) is disabled. After the package test is completed, go test prints a summary line showing the test status (“OK” or “fail”), the package name, and the time consumed.

The second, called the package list pattern, occurs when go test is called with explicit package parameters (for example, “go test math,” “go test. /…” or even “go test.”). In this mode, go test compiles and tests each package listed in the command line. If a package test passes, go test prints only the final “OK” summary line. If a package test fails, go test prints the full test output. If called with the – bench or – V flag (seeTestFlag theme — test flagEven if the package test is passed, go test prints the full output to show the required benchmark results or detailed logs. After the package test of all listed packages is completed, and their output is printed. If any package test fails, go test prints the final “fail” status.

Only in package list mode, go test caches the successful package test results to avoid unnecessary test repetition. When the test results can be recovered from the cache, go test will redisplay the previous output instead of running the test binaries again. When this happens, go test prints “(cached)” in the summary line instead of the consumed time.

The rule of cache matching is that the run only involves the same test binaries, and the flags in the command line come from a limited set of “cacheable” test flags, defined as – CPU, – list, – parallel, – run, – short and – V. If go test runs with any test or non test flags that are not in this collection, the results are not cached. To disable test caching, use a test flag or parameter other than the cacheable flag. The usual way to explicitly disable the test cache is to use – count = 1. Tests that open files or query environment variables in the package source code root (usually $gopath) only match future test runs with unchanged files and environment variables. Cached test results are considered to be executed immediately, so a successful package test result is cached and the – timeout setting is ignored when reused.

In addition to the build flag, “go test” itself handles the following flags:

  • -Args: pass the remaining parameters in the command line (all parameters after – args) to the test binary, which will not be parsed or modified. Because the flag uses the remaining parameters on the command line, the list of packages, if any, must appear before the flag.
  • -c: Compile test binaries as pkg.test It does not run (PKG is the last element of the package’s import path). The file name can be modified by the – O flag.
  • -Exec xprog: use xprog to run test binaries. Its behavior is the same as “go run.”. See “go help run” for more information.
  • -i: Install dependent packages for testing. Do not run the test.
  • -JSON: convert the test output to a JSON format suitable for automated execution. For more information on encoding, see “go doc test2json.”.
  • -O file: compile the test binary to the file with the specified name. The test will still run (unless – C or – I is specified).

Test binaries also accept flags that control test execution; these parameters can also be used by “go test.”. See “go help testFlag” for more information.

For more information about build flags, see “go help build.”. For more information about specifying packages, see “go help packages.”.

See: go build, go vet.

Go tool — runs the specified go tool

go tool [-n] command [args...]

Run the go tool command specified by the parameter. Print a list of known tools without parameters.

Logo:

  • -n: Print the command that will be executed, but do not execute it.

For more information about each tool command, see “go doc CMD”/”。

Go version — print go version

go version [-m] [-v] [file ...]

Print the build information of go executable.

The go version report is used to build the go version of each executable with the specified name.

If no file is specified on the command line, go version prints its own version information.

Logo:

  • -m: When available, ask go version to print the embedded module version information of each executable. In the output, the module information contains multiple lines following the version line, each line indented by a leading tab.
  • -v: If you specify a directory, go version recursively traverses the directory, looks for recognizable go binaries and reports their versions. By default, go version does not report unrecognized files found during a directory scan. -The V flag causes it to report unrecognized files.

See: go doc runtime/ debug.BuildInfo 。

Go vet — report possible errors in the package

go vet [-n] [-x] [-vettool prog] [build flags] [vet flags] [packages]

Run the go vet command on the package with the name specified by the import path.

For more information about vet and its flags, see “go doc CMD / vet.”. For more information about specifying packages, see “go help packages.”. For a list of checkers and their flags, see “go tool vet help.”. For more information about specific checkers such as “printf,” see “go tool vet help printf.”.

Logo:

  • -n: Print the command that will be executed, but do not execute it.

  • -Vettool = prog: select different analysis tools with alternative or additional checks. For example, you can use these commands to build and run the shadow parser:

    go install golang.org/x/tools/go/analysis/passes/shadow/cmd/shadow
    go vet -vettool=$(which shadow)
  • -x: Print the command that will be executed and execute it.

The build flags supported by go vet are those that control package parsing and execution, such as – N, – x, – V, – Tags, and – toolexec. For more information about these flags, see “go help build.”.

See: go FMG, go fix.

Build mode theme — build mode

The “go build” and “go install” commands use the – Buildmode parameter to indicate which object file to build. Currently supported values are:

If not specified, the following build mode can list multiple packages to be built at the same time

  • -Buildmode = Archive: builds the listed non main packages to generate. A files. The main package is ignored.
  • -Buildmode = c-archive: build the listed main package and add all the imported packages to generate the C archive file. Callable symbols are only those functions exported using CGO / / export comment. Only one main package is required to be listed.
  • -Buildmode = c-shared: build the listed main package, add all the imported packages, and generate the C shared library. Callable symbols are only those functions exported using CGO / / export comment. Only one main package is required to be listed.
  • -Buildmode = Default: builds the listed main packages to generate executable files, and builds the listed non main packages to generate. A files (default behavior).
  • -Buildmode = exe: builds the listed main package and all imported packages to generate executable files. Non main packages are ignored.
  • -Buildmode = Pie: build the listed main packages and all imported packages, and generate position independent executables (PIE). Non main packages are ignored.
  • -Buildmode = plugin: build the listed main package, add all the imported packages, and generate the go plug-in. Non main packages are ignored.
  • -Buildmode = shared: merge all listed non main packages to generate a separate shared library, which can be used when building with the – linkshared option. The main package is ignored.

On AIX, when linking a C program that uses a go archive built with – Buildmode = c-archive, you must pass – WL, – bnoobjreorder to the C compiler.

C topic — call between go and C

There are two different ways to call between go and C / C + + code.

The first is the CGO tool, which is part of the go distribution. For information on how to use it, refer to the CGO documentation (go doc CMD / CGO).

The second is swig program, which is a general tool for connecting languages through interfaces. For information about swig, see http://swig.org/ 。 When you run go build, any file with a. Swig extension is passed to swig. Any file with the. Swigcxx extension will be passed to swig using the – C + + option.

When either CGO or swig is used, go build passes all. C,. M,. S, or. S files to the C compiler, and all. CC,. CPP,. Cxx files to the C + + compiler. You can set the CC or cxx environment variables to determine which C or C + + compiler to use in turn.

Cache topic — building and testing caches

The go command caches the build output for reuse in future builds. The default location of cache data is the subdirectory named go build under the current operating system standard user cache directory. Set the GOCACHE environment variable to override the default value and run “go env GOCACHE” to print the current cache directory.

The go command periodically removes recently unused cache data. Run “go clean – cache” to delete all cached data.

Building the cache correctly takes into account changes in go source files, compilers, compiler options, and so on: it is not necessary to explicitly clean up the cache in normal use. However, the build cache does not detect changes to the C library imported by CGO. If you make changes to the C library on your system, you will need to explicitly clean up the cache or use the – a build flag (see “go help build”) to force the rebuild of packages that depend on the updated C library.

The go command also caches successful package test results. See “go help test” for more details. Run “go clean – testcache” to delete all cached test results (excluding cached build results).

The godebug environment variable enables printing debug information about the cache state:

  • Godebug = gocacheverify = 1: causes the go command to bypass the use of any cache entry and instead rebuild everything and check that the result matches the existing cache entry.
  • Godebug = gocachehash = 1: causes the go command to print the input for all the content hashes it uses to build the cache lookup key. The output is lengthy, but can be useful for debugging caches.
  • Godebug = gocachetest = 1: causes the go command to print details of its decision on whether to reuse the cached test results.

Environment topic — environment variables

The go command and the tools it invokes query environment variables for configuration. If the environment variable is not set, the go command uses a reasonable default setting. To view variablesRun “go env””。 To change the default settings, run “go env – W”=”。 The default value modified with “go env – W” is recorded in the go environment variable configuration file stored in a configuration directory for each user, which is similar to os.UserConfigDir Reported. The location of the configuration file can be modified by setting the environment variable goenv, and “go env goenv” prints the valid location, but “go env – W” cannot modify the default location. See “go help env” for more information.

Common environment variables:

  • Gccgo: gccgo command to run for “go build – compiler = gccgo”.
  • Goarch: Architecture or processor for which to compile code. For example, AMD64, 386, arm, ppc64.
  • Gobin: the directory used by the “go install” installation command.
  • GOCACHE: the go command stores the cached information for reuse in future builds.
  • Godebug: enable multiple debugging functions. See “go doc runtime” for details.
  • Goenv: the location of the go environment variable configuration file. Cannot use the “go env – W” setting.
  • Goflags: a blank separated list of – flag = value settings. When a given flag is known by the current command, it will be applied to the go command by default. Each entry must be a separate flag. Because the entry is white space delimited, the flag value must not contain white space. The flags listed in the command line are applied after the list and are therefore overridden.
  • Goinsecure: glob mode of module path prefix (with go’s path.Match , which should always be pulled in an unsafe manner. Only applies to dependencies that are pulled directly.
  • Gonoproxy: see goprivate.
  • Gonosumdb: see goprivate.
  • Goos: the operating system for which to compile code. For example, Linux, Darwin, windows, NetBSD.
  • Gopath: see “go help gopath” for update details.
  • Goprivate: glob mode of module path prefix path.Match , which should always be pulled directly or should not be compared with a checksums database. See “go help module private.”.
  • Goproxy: go module proxy URL. See “go help modules.”.
  • Goroot: the root of the go tree.
  • Gosumdb: the name of the checksum database used, and, optionally, its public key and URL. See “go help module auth.”.
  • Gotmpdir: the go command writes to the directory of temporary source files, packages, and binaries.

Environment variables used with CGO:

  • Ar: the command used to manipulate library archives when built with the gccgo compiler. The default is “ar”.
  • CC: the command used to compile c code.
  • CGO_ Cflags: flag that CGO will pass to the compiler when compiling C code.
  • CGO_ CFLAGS_ Allow: a regular expression that specifies additional flags that are allowed to appear in the ා CGO cflags source code instruction. Does not apply to CGO_ Cflags environment variable.
  • CGO_ CFLAGS_ Disallow: a regular expression that specifies the flag that must be suppressed in the CGO cflags source code instruction. Does not apply to CGO_ Cflags environment variable.
  • CGO_ Cppflags: similar to CGO_ Cflags, but provided to the C preprocessor.
  • CGO_ CPPFLAGS_ Allow: similar to CGO_ CFLAGS_ Allow, but provided to the C preprocessor.
  • CGO_ CPPFLAGS_ Disallow: similar to CGO_ CFLAGS_ Disallow, but provided to the C preprocessor.
  • CGO_ Cxxflags: similar to CGO_ Cflags, but provided to the C + + compiler.
  • CGO_ CXXFLAGS_ Allow: similar to CGO_ CFLAGS_ Allow, but provided to the C + + compiler.
  • CGO_ CXXFLAGS_ Disallow: similar to CGO_ CFLAGS_ Disallow, but provided to the C + + compiler.
  • CGO_ Enabled: whether the CGO command is supported. 0 or 1.
  • CGO_ Fflags: similar to CGO_ Cflags, but provided to the FORTRAN compiler.
  • CGO_ FFLAGS_ Allow: similar to CGO_ CFLAGS_ Allow, but provided to the FORTRAN compiler.
  • CGO_ FFLAGS_ Disallow: similar to CGO_ CFLAGS_ Disallow, but provided to the FORTRAN compiler.
  • CGO_ Ldflags: similar to CGO_ Cflags, but provided to the linker.
  • CGO_ LDFLAGS_ Allow: similar to CGO_ CFLAGS_ Allow, but provided to the linker.
  • CGO_ LDFLAGS_ Disallow: similar to CGO_ CFLAGS_ Disallow, but provided to the linker.
  • Cxx: command for compiling C + + code.
  • FC: command used to compile FORTRAN code.
  • PKG_ Config: path to the PKG config tool.

Architecture specific environment variables:

  • Go386: for goarch = 386, floating-point instruction set. The valid values are 387, SSE2.
  • Goarm: the arm architecture to compile for goarch = arm. The valid values are 5,6,7.
  • Gomips: whether to use floating-point instruction set for goarch = MIPs {, Le}. The valid values are hardload (default), softload.
  • Gomips64: whether to use floating-point instruction set for goarch = MIPS64 {, Le}. The valid values are hardload (default), softload.
  • Gowasm: a comma separated list of experimental web assembly features to use for goarch = wasm. The valid values are satconv and signnext.

Special purpose environment variables:

  • Gccgotoldir: if set, indicates where gccgo tools can be found, such as CGO. The default value is based on how gccgo is configured.
  • GIT_ ALLOW_ Protocol: defined by GIT. Colon separated list of schemes that are allowed to be used with git fetch / clone. If set, any scheme not explicitly mentioned will be considered unsafe by “go get”. Because the variable is defined by git, the default value cannot be set with “go env – W”.
  • GO_ EXTLINK_ Enabled: whether the linker should use external linking mode when – linkmode = auto is used with code that uses CGO. Set to 0 to disable external linking mode and 1 to enable it.
  • GOROOT_ Final: root of the installed go tree, used when it is installed outside its build location. The file name in the stack trace is rewritten from goroot to goroot_ FINAL。

Additional information available from “go env” but not read from environment variables:

  • Goexe: the suffix of executable file name (“. Exe” on windows and “” on other systems).
  • Gogccflags: a blank separated list of parameters provided to the CC command.
  • Gohostarch: go toolchain binary file architecture (goarch).
  • Gohostos: go tool chain binary operating system (goos).
  • Gomod: main module’s go.mod The absolute path of. If module aware mode is enabled but not go.mod , gomod will be os.DevNull “/ dev / null” on UNIX like systems and “nul” on Windows). If module aware mode is disabled, gomod will be an empty string.
  • Gotooldir: the directory where go tools (compile, cover, Doc, etc.) are installed.

Filetype theme — file types

The go command checks the contents of a limited set of files in each directory. It identifies which files to check based on the extension of the file name. These extensions are:

  • . C /. H: C source file. If the package uses CGO or swig, the files are compiled using the operating system’s local compiler (usually GCC); otherwise, they trigger an error.
  • . CC /. CPP /. Cxx /. HH /. HPP /. Hxx: C + + source file. Useful only with CGO or swig, and always compiled with the operating system’s native compiler.
  • . go: go source file.
  • . M: Objective-C source file. Useful only with CGO and always compiled with the operating system’s native compiler.
  • . s /. S: assemble the source file. If the packages use CGO or swig, they will be assembled using the operating system local assembler (usually GCC (SIC)); otherwise, they will be assembled using the go assembler.
  • . swig /. Swigcxx: swig definition file.
  • . syso: system object file.

Each of these types of files, except. Syso, may contain build constraints, but the go command stops scanning for build constraints at the first item in the file that is not an empty line or / – style line comment. See the go / build package documentation for more details.

go.mod Theme—— go.mod file

The module version is defined by the source file tree and has one in its root directory go.mod Documents. When the go command runs, it looks for the current directory and then looks for successive parent directories to find out go.mod , go.mod Mark the root of the main (current) module.

go.mod The file itself is line oriented with / / comments but no / * * / comments. Each line contains a single instruction, consisting of a verb followed by a parameter. For example:

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

The verb is:

  • Module: defines the module path.
  • Go: set the expected language version.
  • Require: a dependency requires a specific module of a given version or later.
  • Exclude: exclude specific module versions from use.
  • Replace: replaces another module version with a different module version.

Exclude and replace are only applied to the go.mod And is ignored in dependencies. For more information, see https://research.swtch.com/vgo-mvs 。

The starting verb can be broken down from adjacent lines to create a block, similar to in go import import:

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

go.mod Files are designed to be either directly edited or easily updated by tools. The “go mod edit” command can be used to parse and edit from programs and tools go.mod Documents. See “go help mod edit.”.

The go command is automatically updated every time it uses the module diagram go.mod To ensure that go.mod Always accurately reflect the actual situation and format it correctly. For example, consider the go.mod Document:

module M

require (
	A v1
	B v1.0.0
	C v1.0.0
	D v1.2.3
	E dev
)

exclude D v1.2.3

The update will rewrite the nonstandard version identifier into semantic Version (semver) format, so V1 of a becomes v1.0.0, and dev of e becomes the last pseudo version number submitted on the dev branch, which may be v0.0.0-20180523231146-b3f5c0f6e5f1.

The update modifies the dependency requirement rule to comply with the exclusion rule, so the dependency requirement on the excluded D v1.2.3 is updated to use the next available version number of D, possibly D v1.2.4 or D v1.3.0.

Updates remove redundant or misleading dependency requests. For example, if a v1.0.0 self dependency requires B v1.2.0 and C v1.0.0, then go.mod The B v1.0.0 dependency requirements are misleading (replaced by a’s requirement for v1.2.0), and their c v1.0.0 dependency requirements are redundant (implied by a’s requirements for the same version), so they will be deleted. If module M contains packages that import packages directly from B or C, the dependency requirements are preserved but updated to the actual version number used.

Finally, the update is reformatted in a canonical format go.mod So that future mechanical modifications will also result in minimal differences.

Because the module diagram defines the meaning of the import statement, any command to load the package is also used and updated accordingly go.mod It includes go build, go get, go install, go list, go test, go mod graph, go mod tidy, go mod why.

The expected language version set by the go instruction determines which language features are available when compiling the module. The language features available in this release will be available. Language features removed in earlier versions or added in subsequent versions will not be available. Note that the language version does not affect the build flag, it is determined by the go release version used.

Gopath topic — gopath environment variable

Gopath is used to parse import statements, which is implemented by go / build package and documents are recorded in go / build package.

The gopath environment variable lists where to look for go code. On UNIX, values are colon separated strings. On windows, values are semicolon separated strings. On Plan 9, the values are a list.

If the environment variable is not set, gopath defaults to a subdirectory named “go” in the user’s home directory ($home / go on UNIX and% userprofile% \ go on Windows), unless the directory contains a go distribution. Run “go env gopath” to see the current gopath.

see https://golang.org/wiki/SettingGOPATH To set the custom gopath.

Each directory listed in gopath must have a specified structure:

The SRC directory contains the source code. The path under SRC determines the import path or executable name.

The PKG directory contains the installed package object files. As in the go tree, each target operating system and architecture pair has its own PKG subdirectory (PKG / goos)_ GOARCH)。

If dir is a directory listed in gopath, the package of source code in dir / SRC / foo / bar can be imported as “foo / bar”, and its compiled form file will be installed in “dir / PKG / goos”_ GOARCH/foo/bar.a”。

The bin directory contains compiled commands. Each command is named after its source code directory, but only takes the last element, not all paths. That is, the command of source code in dir / SRC / foo / quux is installed in dir / bin / quux instead of dir / bin / foo / quux. The “foo /” prefix has been stripped off, so you can add dir / bin to your path to access the installed commands. If the Gobin environment variable is set, the command is installed in its named directory instead of dir / bin. Gobin must be an absolute path.

This is a sample directory layout:

GOPATH=/home/user/go

/home/user/go/
	src/
		foo/
			Bar / (go code in bar package)
			    x.go
			Quux / (go code in main package)
				y.go
	bin/
		Quux (command to install)
	pkg/
		linux_amd64/
			foo/
				Bar. A (installed package object file)

Go searches every directory listed in gopath for source code, but new packages are always downloaded to the first directory in the list.

For example, see https://golang.org/doc/code.html 。

Gopath and modules

When using modules, gopath is no longer used to parse import imports. However, it is still used to save the downloaded source code (in gopath / PKG / MOD) and compiled commands (in gopath / bin).

Internal directory

Code in or below the directory named “internal” can only be imported by code in the directory tree with the parent directory of “internal” as the root. This is the extended version of the directory layout above:

/home/user/go/
	src/
		crash/
			Bang / (go code in Bang package)
				b.go
		Foo / (go code in foo package)
			f.go
			Bar / (go code in bar package)
				x.go
			internal/
				Baz / (go code in Baz package)
					z.go
			Quux / (go code in main package)
				y.go

z. The code in go is imported as “foo / internal / Baz”, but the import statement can only appear in the source file in the subtree with foo as the root. The source files foo / f.go, foo / bar / x.go, foo / quux / y.go can be imported into “foo / internal / Baz”, but the source file crash / bang / b.go can not.

See for details https://golang.org/s/go14internal 。

Vendor directory

Go 1.6 includes support for using local copies of external dependencies to satisfy the import of those dependencies, commonly referred to as using vendor.

Code under the directory named “vendor” can only be imported by code in the directory tree with the parent directory of “vendor” as the root, and only the import path that ignores until and includes the prefix of the vendor element is used.

This is the example from the previous section, but the “internal” directory is renamed “vendor” and a new foo / vendor / crash / bang directory is added:

/home/user/go/
	src/
		crash/
			Bang / (code in Bang package)
				b.go
		Foo / (code in foo package)
			f.go
			Bar / (code in bar package)
				x.go
			vendor/
				crash/
					Bang / (code in Bang package)
						b.go
				Baz / (code in Baz package)
					z.go
			Quux / (code in main package)
				y.go

The same visibility rules as internal are applied, but the code import in z.go is “Baz”, not “foo / vendor / Baz”.

The code in the deeper vendor directory in the source tree is hidden in the higher directory. In the foo rooted subtree, the import of “crash / bang” is resolved as “foo / vendor / crash / bang”, rather than the top-level “crash / bang”.

The code in the vendor directory is not affected by the import path check (see “go help importpath”).

When “go get” checks out or updates the GIT repository, it now also updates the submodules.

The vendor directory does not affect the location of new warehouses that are first checked out by “go get”: they are always placed in the main gopath, never in the vendor subtree.

See for details https://golang.org/s/go15vendor 。

The theme of gopath get — the legacy go get of gopath

go get [-d] [-f] [-t] [-u] [-v] [-fix] [-insecure] [build flags] [packages]

The “go get” command changes behavior based on whether the go command runs in module aware mode or legacy gopath mode. The help text here, even in module aware mode, can be accessed as “go help gopath get”, which describes the operation of “go get” in the legacy gopath mode.

Get downloads packages named by the import path and their dependencies. Then install the package with the specified name, similar to “go install”.

Logo:

  • -d: Stop after the package is downloaded; that is, it causes get to not install the package.
  • -f: Only valid if – u is set, forcing get – u not to verify that each package is checked out from its source code control repository implied by its import path. This will be useful if the fork source code is local.
  • -Fix: run fix tools on downloaded packages before parsing dependencies and building code.
  • -Execute: allows unsafe schemes such as HTTP to pull and resolve custom domain names from the repository. Use with caution.
  • -t: At the same time, download the specified package to build the package required for the test.
  • -u: Use the network to update the named package and its dependencies. By default, get uses the network to check out missing packages, but does not use it to find updates to existing packages.
  • -v: Enable detailed progress and debug output.

Get also accepts build flags to control installation. See “go help build.”.

When a new package is checked out, get creates the target directory gopath / SRC/。 If gopath contains multiple entries, get uses the first. See “go help gopath” for more details.

When checking out or updating a package, get looks for a branch or tag that matches the locally installed version of go. The most important rule is that if the local installation is running version “go1,” get looks for the branch or tag named “go1.”. If no such version exists, it retrieves the default branch of the package.

When go get checks out or updates a git repository, it also updates any git submodules referenced by that repository.

Get never checks out or updates code stored in the vendor directory.

For more information about specifying packages, see “go help packages.”.

For more information about how “go get” finds the downloaded source code, see “go help importpath.”.

This text describes the behavior of get when using gopath to manage source code and dependencies. If, on the contrary, the go command runs in module aware mode, the content of “go help get” will be different. Similarly, the logo and behavior details of get will also change. See “go help modules” and “go help module get.”.

See: go build, go install, go clean.

Goproxy topic — module proxy protocol

A go module proxy is any web server that can respond to get requests for a specific format URL. The request has no query parameter, so even from a fixed file system (including file://URL )The site providing the service can also be a module proxy.

The get request sent to the go module agent is:

  • GET $GOPROXY//@V / list: returns a list of all known versions of a given module, one at a time.
  • GET $GOPROXY//@v/. Info: returns metadata in JSON format for a given version of a given module.
  • GET $GOPROXY//@v/Given module: Return go.mod Documents.
  • GET $GOPROXY//@v/. zip: returns the zip archive of the given version of the given module.
  • GET $GOPROXY//@Latest: with/@v/. info returns JSON formatted metadata about the last known version of a given module in the same format. The last version should be if/@If V / list is empty or not listed, it is the module version that can be used by go command when appropriate./@Latest is optional and may not be implemented by the module proxy.

When the final version of the module is parsed, the go command requests/@V / list, and then, if the appropriate version is not found, request/@latest。 The go command is biased to the following order: the highest semantically released version, the highest semantically released version, and the most recent pseudo version in chronological order. In go 1.12 and earlier, the go command thought that/@The pseudo version in V / list is a pre release version, but not since go 1.13.

To avoid problems when serving from a case sensitive file system,andElement is case coded, replacing each uppercase letter with an exclamation point followed by a corresponding lowercase letter: github.com/Azure Code as github.com/ !azure。

The metadata in JSON format of a given module corresponds to this go data structure, which may be extended in the future:

type Info struct {
    Version string // version string
    Time     time.Time  //Commit time
}

The zip archive for a given version of a given module is a standard zip file, which contains the file tree corresponding to the source code and related files of the module. The path of the archive file is separated by slash. Each file path in the archive file must [email protected]/In the beginning, module and version are replaced directly without case coding. The root of the module file tree corresponds to [email protected]/Prefix.

Even when downloading directly from the version control system, the go command synthesizes explicit info, mod, and zip files and stores them in its local cache $gopath / PKG / mod / cache / download, just as if they were downloaded directly from the agent. The layout of the cache is the same as the proxy URL space, so the service is provided at $gopath / PKG / mod / cache / download (or copy it to) https://example.com/proxy It can make other users use goproxy= https://example.com/proxy Access those cached module versions.

Import path topic — import path syntax

The import path (see “go help packages”) represents packages stored on the local file system. Usually, the import path represents either a standard package (such as “Unicode / utf8”) or in one of the workspacesRelative import pathFor more details, see “go help gopath”).

Relative import path

Import paths that start with. / or.. / are called relative paths. Tool chain supports relative import path as shortcut in two ways.

First, relative paths can be used as shorthand on the command line. If you work in a directory that contains code imported as “Unicode” and want to run tests for “Unicode / utf8,” you can type “go test. / utf8” without specifying the full path. Similarly, in the opposite case, “go test…” will test “Unicode” from the “Unicode / utf8” directory. Relative patterns are also allowed, such as “go test. /…” to test all subdirectories. For more information on schema syntax, see “go help packages.”.

Second, if you are not compiling a go program in the workspace, you can use a relative path in the import statement of the program to refer to nearby code that is also not in the workspace. It’s easier to experiment with small multi package programs out of the usual workspace, but they can’t be installed with “go install” (there’s no workspace to install them), so every time they’re built, they’re rebuilt from scratch. To avoid ambiguity, go programs cannot use relative Import paths in the workspace.

Remote import path

Some import paths also describe how to use the version control system to get the source code for the package.

Some common code hosting sites have specific syntax:

Bitbucket (Git, Mercurial)

	import "bitbucket.org/user/project"
	import "bitbucket.org/user/project/sub/directory"

GitHub (Git)

	import "github.com/user/project"
	import "github.com/user/project/sub/directory"

Launchpad (Bazaar)

	import "launchpad.net/project"
	import "launchpad.net/project/series"
	import "launchpad.net/project/series/sub/directory"

	import "launchpad.net/~user/project/branch"
	import "launchpad.net/~user/project/branch/sub/directory"

IBM DevOps Services (Git)

	import "hub.jazz.net/git/user/project"
	import "hub.jazz.net/git/user/project/sub/directory"

For code hosted on other servers, the import path is either limited by version control type, or the go tool can dynamically pull the import path through HTTP / HTTPS and select one from HTMLTag finds where the code is.

To declare the location of the code,repository.vcs/pathThe import path of the format specifies the given warehouse, with or without the. VCs suffix, the version control system with the specified name, and then the path in the warehouse. The supported version control systems are:

Bazaar      .bzr
Fossil      .fossil
Git         .git
Mercurial   .hg
Subversion  .svn

For example,import "example.org/user/foo.hg"It means that example.org/user/foo or foo.hg The root directory of the mercurial repository,import "example.org/repo.git/foo/bar"It means that example.org/repo or repo.git The foo / bar directory of the GIT repository.

When the version control system supports multiple protocols, each will be tried in turn during the download. For example, GIT downloads try HTTPS: / /, then git + SSH: / /.

By default, downloads are limited to known security protocols (for example, HTTPS, SSH). To override this setting for git downloads, you can set GIT_ ALLOW_ Protocol environment variable (see “go help environment” for more details).

If the import path is not a known code hosting site and there is also a lack of version control qualifiers, the go tool tries to pull the import path through HTTPS / HTTP and then put it in the HTML of the document

Find inlabel.

The meta tag has the following format:

Import prefix is the import path corresponding to the warehouse root. It must be a prefix or an exact match of the packet fetched with “go get”. If it is not an exact match, another HTTP request is generated for the prefix to verifyThe tags are matched.

Meta tags should appear in the file as early as possible. In particular, it should appear before any original JavaScript or CSS to avoid confusing the restricted parser of the go command.

VCs is one of “BZR”, “fossil”, “git”, “Hg”, “SVN”.

Repo root is the root of a version control system that contains a scheme but does not contain the. VCs qualifier.

For example,import "example.org/pkg/foo"Will result in the following requests:

https://example.org/pkg/foo?go-get=1  (preferred)
http://example.org/pkg/foo?go-get=1   (optional, only with - execute)

Suppose the request for this page is https://example.org/exproj?go-get=1 )If the page contains meta tags, go tool will verify https://example.org/?go-get=1 Include the same meta tag and then git clone https://code.org/r/p/exproj Go to gopath / SRC/ example.org 。

When gopath is used, the downloaded package is written to the first directory listed in the gopath environment variable. (see “go help gopath get” and “go help gopath.”)

When a module is used, the downloaded package is stored in the module cache. (see “go help module get” and “go help goproxy.”)

When modules are used, an extra variable in the go import meta tag is identified and better than those that list the version control system. This variable uses “mod” as the VCs in the content value, as follows:

The label indicates that the example.org The path starting from the URL is https://code.org/moduleproxy The module agent available on the pull module. For more information about the proxy protocol, see “go help goproxy.”.

Import path check

When the custom import path function described above is redirected to a known code hosting site, each result package has two possible import paths, using a custom domain name or a known managed site.

If a package statement is immediately followed by a comment in one of these two formats (before the next new line), it is said to have an import comment:

package math // import "path"
package math /* import "path" */

The go command refuses to install a package with an import comment unless the package is referenced by the import path in the import comment. In this way, import comments let package authors ensure that they use a custom import path instead of a direct path to the underlying code hosting site.

The code import path check found in the vendor tree is disabled. This makes it possible to copy the code to an alternate location in the vendor tree without updating the import annotations.

Import path checking is also disabled when using modules. Import path annotations are go.mod Module statement in the file.

For more details, see https://golang.org/s/go14customimport 。

Modules topics – modules, module versions, and more

A module is a collection of associated go packages. Module is the unit of source code exchange and version control. The go command has direct support for working with modules, including recording and resolving dependencies on other modules. The module replaces the old gopath based method to specify which source files to use in a given build.

Module support

The go command contains support for go modules. whenever go.mod Module aware mode is active by default when a file is found in the current directory or a parent directory of the current directory.

The fastest way to use module support is to check out your repository and create it there go.mod File (described in the next section), run the go command in the file tree.

For more fine-grained control, the go command continues to adhere to the temporary environment variable go111module, which can be set to one of three string values: off, on, or auto (the default). If go111module = on, the go command requires the use of modules and never refers to gopath. We call it a command that is module aware or runs in “module aware mode.”. If go111module = off, the go command never uses module support. Instead, it searches the vendor directory and gopath for dependencies; we now call it the “gopath pattern.”. If go111module = auto or not set, the go command enables or disables module support based on the current directory. Include only in current directory go.mod File or include go.mod Module support is enabled only when the file is under the directory.

In module aware mode, gopath no longer defines import meaning during build, but it still stores downloaded dependencies (in gopath / PKG / MOD) and installed commands (in gopath / bin, unless Gobin is set).

Defining modules

The module is in the root of the tree go.mod The go source file tree of the file. contain go.mod The directory of the file is called the module root. Typically, the module root also corresponds to the source code repository root (but generally not required). A module is a collection of all go packages in the module root and its subdirectories, but does not include those that have their own go.mod Subtree of the file.

Module path is the import path prefix corresponding to the module root. go.mod The file defines the module path, and lists the specific versions of other modules that should be used when parsing imports during construction by giving the module path and version.

For example, this go.mod The file declares that the directory containing it is at path example.com/m , which also declares the module dependency golang.org/x/text and gopkg.in/yaml Specific versions of. V2:

module example.com/m

require (
	golang.org/x/text v0.3.0
	gopkg.in/yaml.v2 v2.1.0
)

go.mod Files can also specify alternate and excluded versions that are applied only when building modules directly; they are ignored when modules are merged into larger builds. More about go.mod File, see “go help” go.mod ”。

To start a new module, just create it at the root of the module’s directory tree go.mod File, which contains only module declarations. The “go mod init” command can be used to do this:

go mod init example.com/m

In a project that has used existing dependency management tools such as godep, glide, DEP, etc., “go mod init” will also add a require statement matching the existing configuration.

once go.mod No extra steps are required for the file to exist: go commands such as “go build”, “go test” or even “go list” will automatically add new dependencies to meet the import requirements.

Main module and build list

The “main module” is the module that contains the directory where the go command runs. The go command searches the current directory, or the parent directory of the current directory, or the parent directory of the parent directory, and so on go.mod To find the module root.

Main module go.mod The file defines the exact set of packages available by go command through require, replace and exclude statements. The dependency modules found after passing the require statement also affect the definition of the package collection, but only through its go.mod Require statement for file: any replace and exclude statements in dependent modules are ignored. Therefore, the replace and exclude statements allow the main module to take full control of its own construction and will not be subject to the full control of its dependencies.

The collection of modules that provide the package to build is called the build list. The build list initially contains only the main module. The go command then adds the exact version of the module required by the module dependencies already in the list to the list, recursively until there is no one to add to the list. If multiple versions of a particular module are added to the list, only the last version (sorted based on semantic versions) is retained for use in the build.

The “go list” command provides information about the main module and the build list. For example:

Go list - M ා print the path of the main module
Go list - M - F = {{. Dir}} ා print the root directory of the main module
Go list - m all ා print build list

Maintenance module dependency requirements

go.mod Files mean readable and editable to programmers and tools. The go command updates itself automatically go.mod File to maintain the standard format and the accuracy of the require statement.

Any go command that finds an unfamiliar import looks for the module that contains the import and automatically adds the last version of the module to go.mod 。 Therefore, in most cases, adding an import to the source code and running “go build”, “go test” or even “go list” is enough: as part of the analysis package, the go command will find and parse the import and update it go.mod Documents.

Even when considering only a single package in a module, the go command can determine that a module dependency requirement is missing and must be added. On the other hand, deciding that a module dependency requirement is no longer needed and can be removed requires a complete picture of all packages in the module, across all possible build configurations (architecture, operating system, build flags, etc.). The “go mod tidy” command generates the profile and then adds any missing module dependency requirements and removes the ones that are not needed.

As maintenance go.mod As part of the require statement in, the go command tracks which packages are imported directly by the current module and which are indirectly used by other modules. stay go.mod In the file, only used indirectly. The required dependency requirements are marked with a “/ / indirect” comment. Once implied by other direct dependency requirements, indirect dependency requirements are automatically transferred from go.mod File. Modules that require their own dependencies cannot be explicitly declared when using their own dependencies.

Because of this automatic maintenance, go.mod The information in is the latest, readable description of the build.

“Go get” command update go.mod To modify the version of the module used in the build. The upgrade of one module may implicitly upgrade the others, and similarly, the degradation of one module may implicitly degrade the others. The “go get” command also makes these implied changes. If go.mod Directly modified, commands like “go build” or “go list” assume that the upgrade is intentional and automatically performs all implied upgrades and updates go.mod To reflect it.

The “go mod” command provides additional support for maintaining and understanding modules and go.mod File function. See “go help mod.”.

-The mod build flag provides for updating and using go.mod Additional control.

  • If called with – mod = mod, the go command loads the module from the module cache even if the vendor directory exists.
  • If called with – mod = readonly, the go command does not allow it go.mod Implicit automatic update as described above. On the contrary, when it comes to go.mod When any changes are made, it fails. This setting is used to check go.mod It is most useful not to need updates, such as in continuous integration and test systems. Even with – mod = readonly, the “go get” command allows updates go.mod And the “go mod” command does not use the – mod flag (or any other build flag).
  • If called with – mod = vendor, the go command assumes that the vendor directory contains the correct copy of the dependency and ignores the go.mod Dependency description in.

Pseudo version

go.mod Files and go commands more often use semantic versions as standard formats to describe module versions, so versions can be compared to determine which should be considered earlier or later than another. Module versions similar to v1.2.3 are introduced by marking revision tags on the underlying source code repository. Those without revision labels can be referred to as “pseudo version” of v0.0.0-yyyymmmddhhmmss abcdefabcdef, where the time is the submission time of UTC, and the last suffix is the prefix of the commit hash. The time part ensures that the two pseudo versions can be compared to determine which occurs later. The commit hash marks the underlying commit, and the prefix (in this case, v0.0.0 -) is obtained from the most recent tagged version in the commit graph before this commit.

There are three pseudo version formats:

  • Vx.0.0-yyyymmddhhmmss-abcdefabcdef: used when there is no earlier version with the appropriate major version before the target commit. (this is the original only format, so some older ones go.mod This format is used even for submissions that comply with the labeling rules.)
  • Vx.y.z-pre.0.yyyymmmddhhmmss-abcdefabcdef: used when the most recent commit with version before the target commit is vx.y.z-pre.
  • VX. Y. (Z + 1) – 0. Yyyymmmddhhmmss abcdefabcdef: used when the most recent commit with version before the target commit is VX. Y.z.

The pseudo version is never entered manually: the go command accepts the commit hash and automatically translates it to a pseudo Version (or, if available, a tagged version). This transformation is an example of a module queryModule querySection).

Module query

On the command line and in the main module go.mod The go command in the file accepts “module query” instead of the module version. (in the evaluation of the main module’s go.mod After the query found in the file, the go command updates the file to replace the query with its results).

The fully specified semantic version, such as “v1.2.3”, is evaluated as the specified version.

A semantic version prefix, such as “V1” or “v1.2”, is evaluated as the last available tagged version with that prefix.

Semantic version comparison, such as“=V1.5.6 “, which is evaluated as the latest available tagged version (pair and > = is the earliest version).

The string “latest” matches the last available tagged version, otherwise it is the last unlabeled revision of the underlying source code repository.

The string “upgrade” is similar to “latest”, but if the module’s current dependency requires a later version than the one “latest” would choose (for example, a newer pre release version), “upgrade” will choose a later version instead.

The string “patch” matches the last available tagged version of a module with the same major and minor version numbers as the version required by the current dependency. If there is no current dependency requirement version, “patch” is equivalent to “latest.”.

The revision identifier of the underlying source repository, such as commit hash prefix, revision tag, branch name, will select the specific code revision. If the revision identifier is also used to label the semantic version, the query is evaluated as the semantic version. Otherwise, the query is evaluated as a submitted pseudo version. Note that branches and tags with names that are matched by other query syntax cannot be selected in this way. For example, the query “V2” represents the last version beginning with “V2”, not a branch named “V2”.

Queries tend to be published rather than pre released. For example“

By the main module go.mod The version of the module prohibited by the exclude statement in is considered unavailable and will not be returned by the query.

For example, these commands are all valid:

go get  github.com/gorilla/mux @Latest ා same (@ latest is the default value of "go get")
go get  github.com/gorilla/mux @V1.6.2 ා recorded as v1.6.2
go get  github.com/gorilla/mux @E3702bed2 ා was recorded as v1.6.2
go get  github.com/gorilla/mux @C 856192 ා was recorded as v0.0.0-20180517173623-c85619274f5d
go get  github.com/gorilla/mux @Master # records the current meaning of master

Module compatibility and semantic version control

The go command requires modules to use semantic versions and expects versions to accurately describe compatibility: it assumes that v1.5.4 is a replacement for v1.5.3, v1.4.0, or even v1.0.0 backward compatibility. More generally, the go command expects the package to comply with the import compatibility rule, which is expressed as follows:

“If the old package and the new package have the same import path, the new package must be backward compatible with the old package.”

Because the go command assumes import compatibility rules, a module definition can only set the minimum dependency required version of one of its dependencies: it cannot set the highest or exclude the selected version. However, importing compatibility rules is not a guarantee: it is possible that v1.5.4 is incorrect and is not a replacement for v1.5.3 backward compatibility. Because of this, the go command never upgrades an unrequired module from an older version to a newer version.

In semantic version control, modifying the major version number indicates a lack of backward compatibility with earlier versions. To preserve import compatibility, the go command requires modules with major version V2 or later to use the module path with the major version as the last element. For example, example.com/m Version v2.0.0 of must use a module path example.com/m/v2 And packages in the module will use this path as their import path prefix, as shown in example.com/m/v2/sub/pkg 。 In this way, including the main version in the module path and import path is called “semantic import version control”. A pseudo version of a module with a major version V2 or later begins with that major version, not V0, as in v2.0.0-20180326061214-4fc5987536ef.

As a special case, to gopkg.in/ The first module path continues to use the Convention established on the system: the major version always appears, and it is preceded by a period instead of a slash: gopkg.in/yaml . V1 and gopkg.in/yaml . V2 instead of gopkg.in/yaml and gopkg.in/yaml/v2 。

The go command treats modules with different module paths as irrelevant: they do not exist in the example.com/m and example.com/m/v2 To establish an association between. Modules with different major versions can be used together in a build and remain separate because their packages actually use different import paths.

In semantic version control, the main version V0 is used for initial development, indicating that there is no expectation of stability or backward compatibility. The major version V0 does not appear in the module path because those versions are prepared for v1.0.0 and V1 does not appear in the module path.

Code written before the introduction of semantic import version control conventions may use major version V2 or later to describe the same set of import paths without version used in V0 and v1. To take into account such code, if the source code repository does not go.mod The file tree of is labeled v2.0.0 or later. The version is considered as part of the available version of V1 module, and a + incompatible suffix is given when converting to module version, just as v2.0.0 + incompatible. +The incompatible tag is also applied to pseudo versions generated from this version, as in v2.0.1-0.yyyymmmddhhmmss abcdefabcdef + incompatible.

In general, there are dependencies on V0, pre release, pseudo, and + incompatible versions in the build list (as reported by “go list – all”), which indicates that problems are more likely to occur when upgrading dependencies, because there is no expectation of compatibility for them.

For more information about semantic import versioning, see https://research.swtch.com/vgo-import For more information about semantic versioning, see https://semver.org/ 。

Module code layout

Currently, for information on how to map source code from a version control system to a module file tree, see https://research.swtch.com/vgo-module 。

Module download and verification

Depending on the settings of the goproxy environment variable (see “go help env”), the go command can pull modules from the proxy or directly to the source code control server. The default setting for goproxy is“ https://proxy.golang.org , direct “means that it attempts to mirror from the go module running by Google, and returns the direct connection if the agent reports that it does not have the module (HTTP Error 404 or 410). For privacy policy on services, see https://proxy.golang.org/privacy 。 If goproxy is set to the string “direct”, the download uses a direct connection to the source control server. Set goproxy to “off” to prohibit downloading modules from any source. Otherwise, goproxy expects a comma separated list of module proxy URLs, in which case the go command will pull modules from those proxies. For each request, the go command attempts each proxy in turn, moving to the next only if the current proxy returns an HTTP response of 404 or 410. The string “direct” can appear in the proxy list, causing the lookup point to attempt a direct connection in the search. Any agents listed after “direct” are never queried.

The goprivate and gonoproxy environment variables allow the proxy to be bypassed for the selected module. See “help module” for more information.

Regardless of the source of the module, the go command checks the download results against known checksums to find unexpected changes in the content of any particular module version from one day to the next. This proofreading first looks at the current module’s go.sum File, but is backed back to the go checksums database, which is controlled by the gosumdb and gonosumdb environment variables. See “go help module auth” for more information.

For more information about the proxy protocol and the cached download package format, see “go help goproxy.”.

Module and using vendor

When using modules, the go command completely ignores the vendor directory.

By default, the go command satisfies the dependency by downloading modules from its source and using those downloaded copies (after validation, as described in the previous section). To allow interoperability with older versions of go, or to ensure that all files used by the build are kept together in a separate file tree, “go mod vendor” creates a directory named vendor at the root of the main module and stores all packages of dependent modules there, which need to be used to support building and testing packages in the main module.

To use the top-level vendor directory of the main module to satisfy the dependency for build (the usual network source and local cache are prohibited), use “go build – mod = vendor”. Note that only the top-level vendor directory of the main module is used; vendor directories in other locations are still ignored.

Get module — get module

This topic describes the behavior of using modules to manage source code and dependenciesGo get — add the dependency package to the current module and install itThe behavior of gopath is described inThe theme of gopath get — the legacy go get of gopathSection.)

Module auth theme — using go.sum Module verification of

The go command attempts to verify each downloaded module to see if the bits downloaded today for a particular module version match those downloaded yesterday. This ensures repeatable builds and discovers the introduction of unexpected modifications, whether malicious or not.

At the root of each module, and go.mod Together, the go command maintains a go.sum Which contains the encrypted checksums that the module depends on.

go.sum The format of each row in is three fields:

[/go.mod]

Each known module version in go.sum Two lines are generated in the file. The first line gives the hash of the file tree for the module version. In the second line, add “/ go.mod ”After the version version is given, only the module version is given (may be composite) go.mod Hash of the file. be confined only to go.mod That allows you to download and verify the version of the module used to calculate the dependency graph go.mod File, do not need to also download the source code of all modules.

Hash hash in the format “H”Start with the algorithm prefix for. The only defined algorithm prefix is “H1:” which uses SHA-256.

Module verification failed

The go command maintains a cache of downloaded packages and calculates and records the encrypted checksums of each package during the download//@v/.ziphash)。 In normal operation, the go command changes the go.sum Files and these precomputed checksums, rather than recalculating them each time a command is called. The “go mod verify” command checks that the cached copy downloaded by the module still matches its record’s checksums and go.sum Entry in.

In daily development, the checksums for a given module version should never change. Each time a dependency is used by a given master module, the go command changes its local cached copy — whether recently downloaded or not — to the master module’s go.sum Proofreading. If the checksums do not match, the go command reports the mismatch as a security error and refuses to run the build. When this happens, proceed cautiously: unexpected code changes mean that today’s build will not match yesterday’s, and unexpected changes cannot be useful.

If the go command reports go.sum The code downloaded for the reported version of the module does not match the code used in previous builds of the main module. It’s important to find out what the correct checksums are at this point go.sum Is it wrong or the downloaded code is wrong. usually go.sum It’s true: you want to use the same code you used yesterday.

If the downloaded module is not already in go.sum The go command queries the go check sum database to pull the expected module go.sum that ‘s ok. If the downloaded code does not match those lines, the go command reports the mismatch and exits. Attention, yes, it’s already there go.sum The version of the module listed in no longer queries the database.

If the report go.sum It’s always worth investigating why the code downloaded today is different from that downloaded yesterday.

The gosumdb environment variable marks the name of the used checksums database and, optionally, its public key and URL, as follows:

GOSUMDB="sum.golang.org"
GOSUMDB="sum.golang.org+"
GOSUMDB="sum.golang.org+ https://sum.golang.org"

The go command knows sum.golang.org Public key, and name sum.golang.google .cn (available in Chinese mainland) connected to sum.golang.org Checksums database; using any other database requires an explicit public key. The default URL is “HTTPS: / /” followed by the database name.

Gosumdb defaults to“ sum.golang.org ”For the go checksums database run by Google. For privacy policy on services, see https://sum.golang.org/privacy 。

If gosumdb is set to “off”, or if “go get” is called with the – execute flag, the checksums database is not queried and all unrecognized modules are accepted at the expense of verifying the security guarantee for repeatable downloads of all modules. A better way to bypass the checksum database for a particular module is to use the goprivate or gonosumdb environment variables. See “help module” for more information.

The “go env – W” command (see “go help env”) can be used to set these environment variables for subsequent go command calls.

Module private topic — module configuration of non public modules

The go command defaults from proxy.golang.org The public go module on the mirror image download module. No matter what the source is, it will also download the module with the sum.golang.org Public go validation and database validation on. These default behaviors work well for publicly available source code.

The goprivate environment variable controls which modules go commands are considered private (not publicly available) and should therefore not use agents or checksums databases. The variable is the glob pattern of the module path prefix (with go’s path.Match A comma separated list. For example,

GOPRIVATE=*.corp.example.com,rsc.io/private

The go command is the first mock exam to prefix any module that matches any pattern. git.corp.example .com/xyzzy、 rsc.io/private , rsc.io/private/quux 。

Goprivate environment variables may also be used by other tools to mark non-public modules. For example, the editor can use goprivate to decide whether to hyperlink the package import to the godoc.org Page.

For fine-grained control of module download and validation, gonoproxy and gonosumdb accept the same type of glob list and override goprivate to make specific decisions on whether to use the proxy or not and the checksum database respectively.

For example, if the company runs a module agent that provides private module services, users can use the following to configure go:

GOPRIVATE=*.corp.example.com
GOPROXY=proxy.example.com
GONOPROXY=none

This tells the go command and other tools to corp.example.com The module at the beginning of the subdomain name is private, but a company agent should be used for downloading both public and private modules, because gonoproxy has been set to override goprivate by not matching the pattern of any module.

The “go env – W” command (see “go help env”) can be used to set these environment variables for subsequent go command calls.

Packages topic — package list and schema

Many commands apply to a package collection:

go action [packages]

Usually, [packages] is a list of import paths.

An import path that is a root path or an import path that begins with an. Or.. element is resolved to a file system path and represents a package in that directory.

Otherwise, for some dirs listed in the gopath environment variable, the import path P represents the packages found in the dir / SRC / P directory (see “go help gopath” for more details).

If no import path is given, the operation applies to the package in the current directory.

The path has four reserved names that should not be used for packages built with the go tool:

  • “All”: extends to all packages found in all gopath trees. For example, “go list all” lists all packages on the local system. When using a module, “all” extends to all packages in the master module and its dependencies, including the dependencies required for any of these tests.
  • “CMD”: the command extended to go warehouse and its internal library.
  • “Main”: represents the top-level package in a stand-alone executable.
  • “STD”: similar to all but only extended to packages in the standard go library.

Import paths starting with “CMD /” only match the source code in the go repository.

The import path is a pattern if it contains one or more “…” wildcards, each of which can match any string, including empty strings and strings with slashes. Such a pattern extends to all package directories found in the gopath tree with name matching patterns.

In order to make the common mode more convenient, there are two special cases. First, the /… At the end of the pattern can match an empty string, so net /… Matches net and packages in its subdirectories, such as net / HTTP. Second, any slash separated pattern element that contains wildcards never participates in the matching of the “vendor” element in the vendor package path, so. /… Does not match packages in the subdirectories of. / vendor or. / mycode / vendor, but. / vendor /… And. / mycode / vendor /… Can. Note, however, that the directory with its own code named vendor is not a vendor package: CMD / vendor may be a command named vendor, and the pattern CMD /… Matches. For more information about using vendor, see golang.org/s/go15vendor 。

The import path can also name the downloaded package to be downloaded from the remote repository. Run “go help importpath” for details.

Each package in the program must have a unique import path. By convention, this is done by starting each path with a unique prefix that belongs to you. For example, the paths used within Google start with “Google” and the paths to remote repositories start with the path of the code, for example“ github.com/user/repo ”。

A package in a program does not have to have a unique package name, but there are two reserved package names with special meanings. The name main stands for a command, not a library. Commands are built as binary and cannot be imported. The name documentation represents a document in a directory that is not a go program. Files in the documentation package are ignored by the go command.

As a special case, if the package list is a list of. Go files in a single directory, the command is applied to a single composite package that just consists of those files, ignoring any build constraints in those files and ignoring any other files in the directory.

With “.” or “U” The initial directory and file name are ignored by the go tool, as is the directory named “testdata.”.

TestFlag theme — test flag

The “go test” command accepts the flags applied to “go test” itself and to the generated test binaries.

Several control performance analysis (profiling) in the flag and write the file suitable for “go tool pprof” performance analysis execution; for more information, run “go tool pprof – H”. Pprof — alloc_ space、–alloc_ objects、–show_ The bytes option controls how the information is rendered.

The following flags are identified by the “go test” command and control the execution of any test:

(Note: in the following notation, test (most) refers to test, benchmark refers to benchmark, example refers to example, and performance analysis refers to profile.)

  • -Bench regexp: run only those benchmarks that match regular expressions. By default, benchmarks are not run. To run all benchmarks, use “- bench.” or “- bench =”. Regular expressions are separated into a series of regular expressions by parenthesized slash (/) characters, and each part of the identifier of the benchmark must match the corresponding element in the sequence, if any. The possible parent of the match is run with B.N = 1 to identify the child benchmark. For example, given – bench = x / y, the top-level benchmark matches X and runs with B.N = 1 to find any child benchmark that matches y, which is the item that will all run later.

  • -Bench time t: run enough iterations for each benchmark to consume time t, which is specified as time.Duration (for example, – benchtime 1h30s). The default value is 1 second (1 s). The special syntax NX means to run the benchmark n times (for example, – benchtime 100x).

  • -Count N: run each test and benchmark n times (the default is 1). If – CPU is set, run n times for each gomaxprocs value. Instances always run only once.

  • -Cover: enables coverage analysis. Note that because coverage analysis works by annotating source code before compilation, compilation and test failures that enable coverage analysis may report line numbers that do not correspond to the original source code.

  • -Covermode, set, count, atomic: sets the coverage analysis mode of the package under test. The default is set unless – race is enabled, in which case it is atomic. The values are:

    • Set (bool): does this statement run?
    • Count (int): how many times does this statement run?
    • Atomic (int): count, but correct in multithreaded testing; significantly higher consumption.

    Set – cover.

  • -Coverpkg, pattern1, pattern2, pattern3: apply coverage analysis to each test of packages that match patterns. By default, only the packages tested are analyzed for each test. For a description of the package pattern, see “go help packages.”. Set – cover.

  • -CPU 1,2,4: specify gomaxprocs runtime.GOMAXPROCS A list of values from which a test or benchmark is executed. The default is the current value of gomaxprocs.

  • -Fail fast: no new tests are started after the first test fails.

  • -List regexp: lists tests, benchmarks, or instances that match a regular expression. No tests, benchmarks, or instances will be run. This only lists the top-level tests. No subtests or subbenchmarks will be shown.

  • -Parallel n: allows parallel execution of test functions calling T. parallel. The value of this flag is the maximum value of tests that run simultaneously; by default, it is set to the value of gomaxprocs. Note that – parallel only applies to a single test binary. Depending on the setting of the – P flag (see “go help build”), the “go test” command may also run tests in parallel for multiple packages.

  • -Run regexp: run only those tests and instances that match regular expressions. For the test, the regular expression is separated into a series of regular expressions by a bracketed slash (/) character, and each part of the identifier of the test must match the corresponding element in the sequence, if any. Note that the possible parents of a match also run, so – run = x / y matches, runs, and reports the results of all tests that match x, even if they don’t have child tests that match y, because they must be run to find those child tests.

  • -Short: Tell long running tests to shorten their run time. The default is off, but in the all.bash It is set during runtime, so installing the go tree can run healthy checks but does not take the time to run detailed tests.

  • -Timeout D: if the test binary runs longer than the duration D, it will panic. If D is 0, the timeout is disabled. The default is 10 minutes (10m).

  • -v: Detailed output: log all tests while the test is running. Even if the test is successful, all text generated by log and logf calls is printed.

  • -Vet list: configure the “go vet” call of the “go test” runtime to use a comma separated list of vet checks. If the list is empty, “go test” runs “go vet” with a carefully designed checklist that is always considered worth mentioning. If the list is “off,” “go test” will not run “go vet” at all.

The following flags are also identified by “go test” and can be used to analyze the performance of the test during execution:

  • -Benchmem: prints memory allocation statistics for the benchmark.
  • -blockprofile block.out : when all tests are completed, write goroutine blocking performance analysis to the specified file. The test binary is written as – C.
  • -Blockprofilerate n: called by using n runtime.SetBlockProfileRate To control the details provided in goroutine blocking performance analysis. See “go Doc” runtime.SetBlockProfileRate ”。 The purpose of performance analyzer is to sample blocking events every n nanoseconds. By default, if- test.blockprofile Without this flag, all blocking events will be recorded, which is equivalent to- test.blockprofilerate=1 。
  • -coverprofile cover.out : write coverage performance analysis to file after all tests pass. Set – cover.
  • -cpuprofile cpu.out : writes CPU performance analysis to the specified file before exiting. The test binary is written as – C.
  • -memprofile mem.out : write memory allocation performance analysis to file after all tests pass. The test binary is written as – C.
  • -Memprofilerate n: by setting runtime.MemProfileRate Enable more accurate (and expensive) memory allocation performance analysis. See “go Doc” runtime.MemProfileRate ”。 To perform a performance analysis of all memory allocations, use the- test.memprofilerate=1 。
  • -mutexprofile mutex.out : writes mutex contention performance analysis to the specified file when all tests are completed. The test binary is written as – C.
  • -Mutex profile fragment n: samples one of n goroutine stack traces that hold contention mutex.
  • -Outputdir Directory: put the output file of performance analysis in the specified directory, which is the directory of “go test” by default.
  • -trace trace.out : writes execution trace information to the specified file before exiting.

Each of these flags can also be recognized with an optional “test.” prefix, as in – test. V. However, when the generated test binary is called directly (“the result of go test – C”), the prefix is mandatory.

As appropriate, before calling the test binary, the “go test” command rewrites or removes recognized flags before and after the optional package list.

For example, commandsgo test -v -myflag testdata -cpuprofile=prof.out -xThe test binary will be compiled and thepkg.test -test.v -myflag testdata -test.cpuprofile=prof.outThe run (- x flag is removed because it applies only to the execution of the go command, not to the test itself).

Test flags that generate performance analysis (in addition to those used for coverage) also keep test binaries in the pkg.test To be used when analyzing performance analysis results.

When “go test” runs the test binary, it runs in the corresponding package source code directory. Depending on the test, you may need to do the same thing when calling the generated test binary directly.

The list of command line packages, if present, must appear before any flags not recognized by the go test command. Continuing with the example above, the package list should have appeared before – myFlag, but it can appear on either side of – V.

When “go test” runs in package list mode, “go test” caches the successful package test results to avoid unnecessary repetition of tests. To disable test caching, use any test flag or parameter other than the cacheable flag. The custom way to explicitly disable the test cache is to use – count = 1.

To avoid arguments from the test binary being resolved to a known flag or package name, use – args (see “go help test”), which passes the rest of the command line to the test binary without parsing or modifying it.

For example, commandsgo test -v -args -x -vThe test binary will be compiled and thepkg.test -test.v -x -vfunction. Similarly,go test -args mathThe test binary will be compiled and thepkg.test mathfunction.

In the first example, – X and the second – V are passed unmodified to the test binary and have no effect on the go command itself. In the second example, the parameter math is passed to the test binary instead of being parsed into a package list.

Testfunc topic — test function

The “go test” command is expected to be in the*_ test.go ”Tests, benchmarks, and sample functions are found in the file.

The test function is a named testxx (XX does not start with a lowercase letter) and should have the following characteristics:

func TestXxx(t *testing.T) { ... }

The benchmark function is a benchmark XX and should have the following characteristics:

func BenchmarkXxx(b *testing.B) { ... }

Example functions are similar to test functions, but instead of using * testing. T to report success or failure, they are printed to os.Stdout 。 If the last comment in the function begins with “output:” then the output is compared exactly with the comment (see the example below). If the last comment starts with “unordered output:” then the output is compared to the comment, but the order of the lines is ignored. Instances without such annotations are compiled but not executed. Instances without text after “output:” are compiled, executed, and expected to produce no output.

Godoc displays the function body of examplexx to demonstrate the use of function, constant, or variable XX. An example of a method m that receives type T or * t is named examplet_ M。 There may be more than one instance of a given function, constant, or variable_ XXX is a suffix that does not begin with a capital letter.

This is an example of an example:

func ExamplePrintln() {
	Println("The output of\nthis example.")
	// Output: The output of
	// this example.
}

This is another example of ignoring the output order:

func ExamplePerm() {
	for _, value := range Perm(4) {
		fmt.Println(value)
	}

	// Unordered output: 4
	// 2
	// 1
	// 3
	// 0
}

The entire test file will be presented as an example when it contains a single instance function, at least one other function, type, variable or constant declaration, without test or benchmark function.

For more information, see the documentation for the testing package.

Recommended Today

Construction of Vue development environment and project creation under mac

start First of all, let’s take a look at the overall development environment of Vue. Homebrew: package manager under MAC system, similar to apt get under Linux, windows control panel – install and remove program Node.jsJavaScript runtime, which is similar to simultaneous interpretation in international conferences, can’t run various programming languages directly between different systems […]