Golang的标准命令简述
作者:尹正杰
版权声明:原创作品,谢绝转载!否则将追究法律责任。
Go本身包含了大量用于处理Go程序的命令和工具。go命令就是其中最常见的一个,它有许多子命令,接下来就跟随博主一起了解一下吧~
一.go build
1>.go build 子命令功能概述
用于编译指定的代码包括Go语言源码文件。
命令源码文件会编译生成可执行文件,并存放在命令指令的目录或指定目录下。
而库源码文件被编译后,则不会在非临时目录中留下任何文件。
2>.查看帮助信息
C:\Users\yinzhengjie>go help build usage: go build [-o output] [-i] [build flags] [packages] Build compiles the packages named by the import paths, along with their dependencies, but it does not install the results. If the arguments to build are a list of .go files from a single directory, build treats them as a list of source files specifying a single package. When compiling packages, build ignores files that end in \'_test.go\'. When compiling a single main package, build writes the resulting executable to an output file named after the first source file (\'go build ed.go rx.go\' writes \'ed\' or \'ed.exe\') or the source code directory (\'go build unix/sam\' writes \'sam\' or \'sam.exe\'). The \'.exe\' suffix is added when writing a Windows executable. When compiling multiple packages or a single non-main package, build compiles the packages but discards the resulting object, serving only as a check that the packages can be built. The -o flag forces build to write the resulting executable or object to the named output file or directory, instead of the default behavior described in the last two paragraphs. If the named output is a directory that exists, then any resulting executables will be written to that directory. The -i flag installs the packages that are dependencies of the target. The build flags are shared by the build, clean, get, install, list, run, and test commands: -a force rebuilding of packages that are already up-to-date. -n print the commands but do not run them. -p n the number of programs, such as build commands or test binaries, that can be run in parallel. The default is the number of CPUs available. -race enable data race detection. Supported only on linux/amd64, freebsd/amd64, darwin/amd64 and windows/amd64. -msan enable interoperation with memory sanitizer. Supported only on linux/amd64, linux/arm64 and only with Clang/LLVM as the host C compiler. -v print the names of packages as they are compiled. -work print the name of the temporary work directory and do not delete it when exiting. -x print the commands. -asmflags \'[pattern=]arg list\' arguments to pass on each go tool asm invocation. -buildmode mode build mode to use. See \'go help buildmode\' for more. -compiler name name of compiler to use, as in runtime.Compiler (gccgo or gc). -gccgoflags \'[pattern=]arg list\' arguments to pass on each gccgo compiler/linker invocation. -gcflags \'[pattern=]arg list\' arguments to pass on each go tool compile invocation. -installsuffix suffix a suffix to use in the name of the package installation directory, in order to keep output separate from default builds. If using the -race flag, the install suffix is automatically set to race or, if set explicitly, has _race appended to it. Likewise for the -msan flag. Using a -buildmode option that requires non-default compile flags has a similar effect. -ldflags \'[pattern=]arg list\' arguments to pass on each go tool link invocation. -linkshared link against shared libraries previously created with -buildmode=shared. -mod mode module download mode to use: readonly or vendor. See \'go help modules\' for more. -pkgdir dir install and load all packages from dir instead of the usual locations. For example, when building with a non-standard configuration, use -pkgdir to keep generated packages in a separate location. -tags tag,list a comma-separated list of build tags to consider satisfied during the build. For more information about build tags, see the description of build constraints in the documentation for the go/build package. (Earlier versions of Go used a space-separated list, and that form is deprecated but still recognized.) -trimpath remove all file system paths from the resulting executable. Instead of absolute file system paths, the recorded file names will begin with either "go" (for the standard library), or a module path@version (when using modules), or a plain import path (when using GOPATH). -toolexec \'cmd args\' a program to use to invoke toolchain programs like vet and asm. For example, instead of running asm, the go command will run \'cmd args /path/to/asm <arguments for asm>\'. The -asmflags, -gccgoflags, -gcflags, and -ldflags flags accept a space-separated list of arguments to pass to an underlying tool during the build. To embed spaces in an element in the list, surround it with either single or double quotes. The argument list may be preceded by a package pattern and an equal sign, which restricts the use of that argument list to the building of packages matching that pattern (see \'go help packages\' for a description of package patterns). Without a pattern, the argument list applies only to the packages named on the command line. The flags may be repeated with different patterns in order to specify different arguments for different sets of packages. If a package matches patterns given in multiple flags, the latest match on the command line wins. For example, \'go build -gcflags=-S fmt\' prints the disassembly only for package fmt, while \'go build -gcflags=all=-S fmt\' prints the disassembly for fmt and all its dependencies. For more about specifying packages, see \'go help packages\'. For more about where packages and binaries are installed, run \'go help gopath\'. For more about calling between Go and C/C++, run \'go help c\'. Note: Build adheres to certain conventions such as those described by \'go help gopath\'. Not all projects can follow these conventions, however. Installations that have their own conventions or that use a separate software build system may choose to use lower-level invocations such as \'go tool compile\' and \'go tool link\' to avoid some of the overheads and design decisions of the build tool. See also: go install, go get, go clean. C:\Users\yinzhengjie>
3>.使用案例
二.go clean
1>. go clean子命令功能概述
用于清理因执行其它go命令而一路留下来的临时目录和文件。
2>.查看帮助信息
C:\Users\yinzhengjie>go help clean usage: go clean [clean flags] [build flags] [packages] Clean removes object files from package source directories. The go command builds most objects in a temporary directory, so go clean is mainly concerned with object files left by other tools or by manual invocations of go build. If a package argument is given or the -i or -r flag is set, clean removes the following files from each of the source directories corresponding to the import paths: _obj/ old object directory, left from Makefiles _test/ old test directory, left from Makefiles _testmain.go old gotest file, left from Makefiles test.out old test log, left from Makefiles build.out old test log, left from Makefiles *.[568ao] object files, left from Makefiles DIR(.exe) from go build DIR.test(.exe) from go test -c MAINFILE(.exe) from go build MAINFILE.go *.so from SWIG In the list, DIR represents the final path element of the directory, and MAINFILE is the base name of any Go source file in the directory that is not included when building the package. The -i flag causes clean to remove the corresponding installed archive or binary (what \'go install\' would create). The -n flag causes clean to print the remove commands it would execute, but not run them. The -r flag causes clean to be applied recursively to all the dependencies of the packages named by the import paths. The -x flag causes clean to print remove commands as it executes them. The -cache flag causes clean to remove the entire go build cache. The -testcache flag causes clean to expire all test results in the go build cache. The -modcache flag causes clean to remove the entire module download cache, including unpacked source code of versioned dependencies. For more about build flags, see \'go help build\'. For more about specifying packages, see \'go help packages\'. C:\Users\yinzhengjie> C:\Users\yinzhengjie>
3>.使用案例
三.go doc
1>.go doc子命令功能概述
用于显示Go语言代码包以及程序实体的文档。
2>.查看帮助信息
C:\Users\yinzhengjie>go help doc usage: go doc [-u] [-c] [package|[package.]symbol[.methodOrField]] Doc prints the documentation comments associated with the item identified by its arguments (a package, const, func, type, var, method, or struct field) followed by a one-line summary of each of the first-level items "under" that item (package-level declarations for a package, methods for a type, etc.). Doc accepts zero, one, or two arguments. Given no arguments, that is, when run as go doc it prints the package documentation for the package in the current directory. If the package is a command (package main), the exported symbols of the package are elided from the presentation unless the -cmd flag is provided. When run with one argument, the argument is treated as a Go-syntax-like representation of the item to be documented. What the argument selects depends on what is installed in GOROOT and GOPATH, as well as the form of the argument, which is schematically one of these: go doc <pkg> go doc <sym>[.<methodOrField>] go doc [<pkg>.]<sym>[.<methodOrField>] go doc [<pkg>.][<sym>.]<methodOrField> The first item in this list matched by the argument is the one whose documentation is printed. (See the examples below.) However, if the argument starts with a capital letter it is assumed to identify a symbol or method in the current directory. For packages, the order of scanning is determined lexically in breadth-first order. That is, the package presented is the one that matches the search and is nearest the root and lexically first at its level of the hierarchy. The GOROOT tree is always scanned in its entirety before GOPATH. If there is no package specified or matched, the package in the current directory is selected, so "go doc Foo" shows the documentation for symbol Foo in the current package. The package path must be either a qualified path or a proper suffix of a path. The go tool\'s usual package mechanism does not apply: package path elements like . and ... are not implemented by go doc. When run with two arguments, the first must be a full package path (not just a suffix), and the second is a symbol, or symbol with method or struct field. This is similar to the syntax accepted by godoc: go doc <pkg> <sym>[.<methodOrField>] In all forms, when matching symbols, lower-case letters in the argument match either case but upper-case letters match exactly. This means that there may be multiple matches of a lower-case argument in a package if different symbols have different cases. If this occurs, documentation for all matches is printed. Examples: go doc Show documentation for current package. go doc Foo Show documentation for Foo in the current package. (Foo starts with a capital letter so it cannot match a package path.) go doc encoding/json Show documentation for the encoding/json package. go doc json Shorthand for encoding/json. go doc json.Number (or go doc json.number) Show documentation and method summary for json.Number. go doc json.Number.Int64 (or go doc json.number.int64) Show documentation for json.Number\'s Int64 method. go doc cmd/doc Show package docs for the doc command. go doc -cmd cmd/doc Show package docs and exported symbols within the doc command. go doc template.new Show documentation for html/template\'s New function. (html/template is lexically before text/template) go doc text/template.new # One argument Show documentation for text/template\'s New function. go doc text/template new # Two arguments Show documentation for text/template\'s New function. At least in the current tree, these invocations all print the documentation for json.Decoder\'s Decode method: go doc json.Decoder.Decode go doc json.decoder.decode go doc json.decode cd go/src/encoding/json; go doc decode Flags: -all Show all the documentation for the package. -c Respect case when matching symbols. -cmd Treat a command (package main) like a regular package. Otherwise package main\'s exported symbols are hidden when showing the package\'s top-level documentation. -src Show the full source code for the symbol. This will display the full Go source of its declaration and definition, such as a function definition (including the body), type declaration or enclosing const block. The output may therefore include unexported details. -u Show documentation for unexported as well as exported symbols, methods, and fields. C:\Users\yinzhengjie> C:\Users\yinzhengjie>
3>.使用案例
四.go env
1>.go env子命令功能概述
用于打印Go语言相关的环境信息。
2>.查看帮助信息
C:\Users\yinzhengjie>go help env usage: go env [-json] [-u] [-w] [var ...] Env prints Go environment information. By default env prints information as a shell script (on Windows, a batch file). If one or more variable names is given as arguments, env prints the value of each named variable on its own line. The -json flag prints the environment in JSON format instead of as a shell script. The -u flag requires one or more arguments and unsets the default setting for the named environment variables, if one has been set with \'go env -w\'. The -w flag requires one or more arguments of the form NAME=VALUE and changes the default settings of the named environment variables to the given values. For more about environment variables, see \'go help environment\'. C:\Users\yinzhengjie> C:\Users\yinzhengjie>
3>.使用案例
五.go fix
1>.go fix子命令功能概述
用于修正指定代码包中的源码文件中包含过时语法和代码调用。
这使得我们在升级Go语言版本时,可以非常方便同步升级程序。
2>.查看帮助信息
C:\Users\yinzhengjie>go help fix usage: go fix [packages] Fix runs the Go fix command on the packages named by the import paths. For more about fix, see \'go doc cmd/fix\'. For more about specifying packages, see \'go help packages\'. To run fix with specific options, run \'go tool fix\'. See also: go fmt, go vet. C:\Users\yinzhengjie>
3>.使用案例
六.go fmt
1>.go fmt子命令功能概述
用于格式化指定代码包中的Go源码文件。
实际上,它是通过执行gofmt命令来实现功能的。
2>.查看帮助信息
C:\Users\yinzhengjie>go help fmt usage: go fmt [-n] [-x] [packages] Fmt runs the command \'gofmt -l -w\' on the packages named by the import paths. It prints the names of the files that are modified. For more about gofmt, see \'go doc cmd/gofmt\'. For more about specifying packages, see \'go help packages\'. The -n flag prints commands that would be executed. The -x flag prints commands as they are executed. To run gofmt with specific options, run gofmt itself. See also: go fix, go vet. C:\Users\yinzhengjie> C:\Users\yinzhengjie>
3>.使用案例
七.go generate
1>.go generate子命令功能概述
用于识别指定代码中源文件中的go:generate注解,并执行其携带的任意命令。
该命令独立利于Go语言标准的编译和安装体系。如果你有需要解析的go:generate注解,就单独运行它。
这个命令非常有用,我们可以用它自动生成或改动源码文件。
2>.查看帮助信息
C:\Users\yinzhengjie>go help generate usage: go generate [-run regexp] [-n] [-v] [-x] [build flags] [file.go... | packages] Generate runs commands described by directives within existing files. Those commands can run any process but the intent is to create or update Go source files. Go generate is never run automatically by go build, go get, go test, and so on. It must be run explicitly. Go generate scans the file for directives, which are lines of the form, //go:generate command argument... (note: no leading spaces and no space in "//go") where command is the generator to be run, corresponding to an executable file that can be run locally. It must either be in the shell path (gofmt), a fully qualified path (/usr/you/bin/mytool), or a command alias, described below. To convey to humans and machine tools that code is generated, generated source should have a line that matches the following regular expression (in Go syntax): ^// Code generated .* DO NOT EDIT\.$ The line may appear anywhere in the file, but is typically placed near the beginning so it is easy to find. Note that go generate does not parse the file, so lines that look like directives in comments or multiline strings will be treated as directives. The arguments to the directive are space-separated tokens or double-quoted strings passed to the generator as individual arguments when it is run. Quoted strings use Go syntax and are evaluated before execution; a quoted string appears as a single argument to the generator. Go generate sets several variables when it runs the generator: $GOARCH The execution architecture (arm, amd64, etc.) $GOOS The execution operating system (linux, windows, etc.) $GOFILE The base name of the file. $GOLINE The line number of the directive in the source file. $GOPACKAGE The name of the package of the file containing the directive. $DOLLAR A dollar sign. Other than variable substitution and quoted-string evaluation, no special processing such as "globbing" is performed on the command line. As a last step before running the command, any invocations of any environment variables with alphanumeric names, such as $GOFILE or $HOME, are expanded throughout the command line. The syntax for variable expansion is $NAME on all operating systems. Due to the order of evaluation, variables are expanded even inside quoted strings. If the variable NAME is not set, $NAME expands to the empty string. A directive of the form, //go:generate -command xxx args... specifies, for the remainder of this source file only, that the string xxx represents the command identified by the arguments. This can be used to create aliases or to handle multiword generators. For example, //go:generate -command foo go tool foo specifies that the command "foo" represents the generator "go tool foo". Generate processes packages in the order given on the command line, one at a time. If the command line lists .go files from a single directory, they are treated as a single package. Within a package, generate processes the source files in a package in file name order, one at a time. Within a source file, generate runs generators in the order they appear in the file, one at a time. The go generate tool also sets the build tag "generate" so that files may be examined by go generate but ignored during build. If any generator returns an error exit status, "go generate" skips all further processing for that package. The generator is run in the package\'s source directory. Go generate accepts one specific flag: -run="" if non-empty, specifies a regular expression to select directives whose full original source text (excluding any trailing spaces and final newline) matches the expression. It also accepts the standard build flags including -v, -n, and -x. The -v flag prints the names of packages and files as they are processed. The -n flag prints commands that would be executed. The -x flag prints commands as they are executed. For more about build flags, see \'go help build\'. For more about specifying packages, see \'go help packages\'. C:\Users\yinzhengjie>
3>.使用案例
package main import ( "fmt" ) //go:generate go run test.go func main() { fmt.Println("博客地址:\n\thttps://www.cnblogs.com/yinzhengjie/") }
八. go get
1>.go get子命令功能概述
用于下载,编译并安装指定的代码包及其依赖包。
从我们自己的代码中中转站或第三方代码库上自动拉取代码,就全靠它了。
2>.查看帮助信息
C:\Users\yinzhengjie>go help get usage: go get [-d] [-f] [-t] [-u] [-v] [-fix] [-insecure] [build flags] [packages] Get downloads the packages named by the import paths, along with their dependencies. It then installs the named packages, like \'go install\'. The -d flag instructs get to stop after downloading the packages; that is, it instructs get not to install the packages. The -f flag, valid only when -u is set, forces get -u not to verify that each package has been checked out from the source control repository implied by its import path. This can be useful if the source is a local fork of the original. The -fix flag instructs get to run the fix tool on the downloaded packages before resolving dependencies or building the code. The -insecure flag permits fetching from repositories and resolving custom domains using insecure schemes such as HTTP. Use with caution. The -t flag instructs get to also download the packages required to build the tests for the specified packages. The -u flag instructs get to use the network to update the named packages and their dependencies. By default, get uses the network to check out missing packages but does not use it to look for updates to existing packages. The -v flag enables verbose progress and debug output. Get also accepts build flags to control the installation. See \'go help build\'. When checking out a new package, get creates the target directory GOPATH/src/<import-path>. If the GOPATH contains multiple entries, get uses the first one. For more details see: \'go help gopath\'. 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 searches for a 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 the repository. Get never checks out or updates code stored in vendor directories. For more about specifying packages, see \'go help packages\'. For more about how \'go get\' finds source code to download, see \'go help importpath\'. This text describes the behavior of get when using GOPATH to manage source code and dependencies. If instead the go command is running in module-aware mode, the details of get\'s flags and effects change, as does \'go help get\'. See \'go help modules\' and \'go help module-get\'. See also: go build, go install, go clean. C:\Users\yinzhengjie> C:\Users\yinzhengjie>
3>.使用案例(使用该命令的前提是你的操作系统得提前安装git环境哟~)
九.go install
1>.go install子命令功能概述
用于编译并安装指定的代码包及其依赖包。
安装包命令源码文件后,代码包所在(GOPATH环境变量中定义)的工作区目录的bin子目录,或者当前环境变量GOBIN指向的目录中会生成相应的可执行文件。
而安装库源码文件后,会在代码包所在的工作目录的pkg子目录生成相应的归档文件。
2>.查看帮助信息
C:\Users\yinzhengjie>go help install usage: go install [-i] [build flags] [packages] Install compiles and installs the packages named by the import paths. Executables are installed in the directory named by the GOBIN environment variable, which defaults to $GOPATH/bin or $HOME/go/bin if the GOPATH environment variable is not set. Executables in $GOROOT are installed in $GOROOT/bin or $GOTOOLDIR instead of $GOBIN. When module-aware mode is disabled, other packages are installed in the directory $GOPATH/pkg/$GOOS_$GOARCH. When module-aware mode is enabled, other packages are built and cached but not installed. The -i flag installs the dependencies of the named packages as well. For more about the build flags, see \'go help build\'. For more about specifying packages, see \'go help packages\'. See also: go build, go get, go clean. C:\Users\yinzhengjie>
3>.使用案例
十.go list
1>.go list子命令功能概述
用于显示指定代码包的信息,它可谓是代码分析的一大便捷工具。
利用Go语言标准代码库代码包"text/template"中规定的模板语法,你可以非常灵活地控制输出信息。
2>.查看帮助信息
C:\Users\yinzhengjie>go help list usage: go list [-f format] [-json] [-m] [list flags] [build flags] [packages] List lists the named packages, one per line. The most commonly-used flags are -f and -json, which control the form of the output printed for each package. Other list flags, documented below, control more specific details. The default output shows the package import path: bytes encoding/json github.com/gorilla/mux golang.org/x/net/html The -f flag specifies an alternate format for the list, using the syntax of package template. The default output is equivalent to -f \'{{.ImportPath}}\'. The struct being passed to the template is: type Package struct { Dir string // directory containing package sources ImportPath string // import path of package in dir ImportComment string // path in import comment on package statement Name string // package name Doc string // package documentation string Target string // install path Shlib string // the shared library that contains this package (only set when -linkshared) Goroot bool // is this package in the Go root? Standard bool // is this package part of the standard Go library? Stale bool // would \'go install\' do anything for this package? StaleReason string // explanation for Stale==true Root string // Go root or Go path dir containing this package ConflictDir string // this directory shadows Dir in $GOPATH BinaryOnly bool // binary-only package (no longer supported) ForTest string // package is only for use in named test Export string // file containing export data (when using -export) Module *Module // info about package\'s containing module, if any (can be nil) Match []string // command-line patterns matching this package DepOnly bool // package is only a dependency, not explicitly listed // Source files GoFiles []string // .go source files (excluding CgoFiles, TestGoFiles, XTestGoFiles) CgoFiles []string // .go source files that import "C" CompiledGoFiles []string // .go files presented to compiler (when using -compiled) IgnoredGoFiles []string // .go source files ignored due to build constraints CFiles []string // .c source files CXXFiles []string // .cc, .cxx and .cpp source files MFiles []string // .m source files HFiles []string // .h, .hh, .hpp and .hxx source files FFiles []string // .f, .F, .for and .f90 Fortran source files SFiles []string // .s source files SwigFiles []string // .swig files SwigCXXFiles []string // .swigcxx files SysoFiles []string // .syso object files to add to archive TestGoFiles []string // _test.go files in package XTestGoFiles []string // _test.go files outside package // Cgo directives CgoCFLAGS []string // cgo: flags for C compiler CgoCPPFLAGS []string // cgo: flags for C preprocessor CgoCXXFLAGS []string // cgo: flags for C++ compiler CgoFFLAGS []string // cgo: flags for Fortran compiler CgoLDFLAGS []string // cgo: flags for linker CgoPkgConfig []string // cgo: pkg-config names // Dependency information Imports []string // import paths used by this package ImportMap map[string]string // map from source import to ImportPath (identity entries omitted) Deps []string // all (recursively) imported dependencies TestImports []string // imports from TestGoFiles XTestImports []string // imports from XTestGoFiles // Error information Incomplete bool // this package or a dependency has an error Error *PackageError // error loading package DepsErrors []*PackageError // errors loading dependencies } Packages stored in vendor directories report an ImportPath that includes the path to the vendor directory (for example, "d/vendor/p" instead of "p"), so that the ImportPath uniquely identifies a given copy of a package. The Imports, Deps, TestImports, and XTestImports lists also contain these expanded import paths. See golang.org/s/go15vendor for more about vendoring. The error information, if any, is type PackageError struct { ImportStack []string // shortest path from package named on command line to this one Pos string // position of error (if present, file:line:col) Err string // the error itself } The module information is a Module struct, defined in the discussion of list -m below. The template function "join" calls strings.Join. The template function "context" returns the build context, defined as: type Context struct { GOARCH string // target architecture GOOS string // target operating system GOROOT string // Go root GOPATH string // Go path CgoEnabled bool // whether cgo can be used UseAllFiles bool // use files regardless of +build lines, file names Compiler string // compiler to assume when computing target paths BuildTags []string // build constraints to match in +build lines ReleaseTags []string // releases the current release is compatible with InstallSuffix string // suffix to use in the name of the install dir } For more information about the meaning of these fields see the documentation for the go/build package\'s Context type. The -json flag causes the package data to be printed in JSON format instead of using the template format. The -compiled flag causes list to set CompiledGoFiles to the Go source files presented to the compiler. Typically this means that it repeats the files listed in GoFiles and then also adds the Go code generated by processing CgoFiles and SwigFiles. The Imports list contains the union of all imports from both GoFiles and CompiledGoFiles. The -deps flag causes list to iterate over not just the named packages but also all their dependencies. It visits them in a depth-first post-order traversal, so that a package is listed only after all its dependencies. Packages not explicitly listed on the command line will have the DepOnly field set to true. The -e flag changes the handling of erroneous packages, those that cannot be found or are malformed. By default, the list command prints an error to standard error for each erroneous package and omits the packages from consideration during the usual printing. With the -e flag, the list command never prints errors to standard error and instead processes the erroneous packages with the usual printing. Erroneous packages will have a non-empty ImportPath and a non-nil Error field; other information may or may not be missing (zeroed). The -export flag causes list to set the Export field to the name of a file containing up-to-date export information for the given package. The -find flag causes list to identify the named packages but not resolve their dependencies: the Imports and Deps lists will be empty. The -test flag causes list to report not only the named packages but also their test binaries (for packages with tests), to convey to source code analysis tools exactly how test binaries are constructed. The reported import path for a test binary is the import path of the package followed by a ".test" suffix, as in "math/rand.test". When building a test, it is sometimes necessary to rebuild certain dependencies specially for that test (most commonly the tested package itself). The reported import path of a package recompiled for a particular test binary is followed by a space and the name of the test binary in brackets, as in "math/rand [math/rand.test]" or "regexp [sort.test]". The ForTest field is also set to the name of the package being tested ("math/rand" or "sort" in the previous examples). The Dir, Target, Shlib, Root, ConflictDir, and Export file paths are all absolute paths. By default, the lists GoFiles, CgoFiles, and so on hold names of files in Dir (that is, paths relative to Dir, not absolute paths). The generated files added when using the -compiled and -test flags are absolute paths referring to cached copies of generated Go source files. Although they are Go source files, the paths may not end in ".go". The -m flag causes list to list modules instead of packages. When listing modules, the -f flag still specifies a format template applied to a Go struct, but now a Module struct: type Module struct { Path string // module path Version string // module version Versions []string // available module versions (with -versions) Replace *Module // replaced by this module Time *time.Time // time version was created Update *Module // available update, if any (with -u) Main bool // is this the main module? Indirect bool // is this module only an indirect dependency of main module? Dir string // directory holding files for this module, if any GoMod string // path to go.mod file for this module, if any GoVersion string // go version used in module Error *ModuleError // error loading module } type ModuleError struct { Err string // the error itself } The default output is to print the module path and then information about the version and replacement 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 struct has a String method that formats this line of output, so that the default format is equivalent to -f \'{{.String}}\'. Note that when a module has been replaced, its Replace field describes the replacement module, and its Dir field is set to the replacement\'s source code, if present. (That is, if Replace is non-nil, then Dir is set to Replace.Dir, with no access to the replaced source code.) The -u flag adds information about available upgrades. When the latest version of a given module is newer than the current one, list -u sets the Module\'s Update field to information about the newer module. The Module\'s String method indicates an available upgrade by formatting the newer version in brackets 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 more convenient to parse.) The -versions flag causes list to set the Module\'s Versions field to a list of all known versions of that module, ordered according to semantic versioning, earliest to latest. The flag also changes the default output format to display the module path followed by the space-separated version list. The arguments to list -m are interpreted as a list of modules, not packages. The main module is the module containing the current directory. The active modules are the main module and its dependencies. With no arguments, list -m shows the main module. With arguments, list -m shows the modules specified by the arguments. Any of the active modules can be specified by its module path. The special pattern "all" specifies all the active modules, first the main module and then dependencies sorted by module path. A pattern containing "..." specifies the active modules whose module paths match the pattern. A query of the form path@version specifies the result of that query, which is not limited to active modules. See \'go help modules\' for more about module queries. The template function "module" takes a single string argument that must be a module path or query and returns the specified module as a Module struct. If an error occurs, the result will be a Module struct with a non-nil Error field. For more about build flags, see \'go help build\'. For more about specifying packages, see \'go help packages\'. For more about modules, see \'go help modules\'. C:\Users\yinzhengjie>
3>.使用案例
十一.go run
1>.go run子命令功能概述
用于编译并允许指定命令源码文件。当你想不生成可执行文件而直接运行命令源码文件时,就需要使用它。
2>.查看帮助信息
C:\Users\yinzhengjie>go help run usage: go run [build flags] [-exec xprog] package [arguments...] Run compiles and runs the named main Go package. Typically the package is specified as a list of .go source files from a single directory, but it may also be an import path, file system path, or pattern matching a single known package, as in \'go run .\' or \'go run my/cmd\'. By default, \'go run\' runs the compiled binary directly: \'a.out arguments...\'. If the -exec flag is given, \'go run\' invokes the binary using xprog: \'xprog a.out arguments...\'. If the -exec flag is not given, GOOS or GOARCH is different from the system default, and a program named go_$GOOS_$GOARCH_exec can be found on the current search path, \'go run\' invokes the binary using that program, for example \'go_nacl_386_exec a.out arguments...\'. This allows execution of cross-compiled programs when a simulator or other execution method is available. The exit status of Run is not the exit status of the compiled binary. For more about build flags, see \'go help build\'. For more about specifying packages, see \'go help packages\'. See also: go build. C:\Users\yinzhengjie> C:\Users\yinzhengjie>
3>.使用案例
十二.go test
1>.go test子命令功能概述
用于测试指定的代码包,前提是该代码包目录中必须存在测试源码文件。
2>.查看帮助信息
C:\Users\yinzhengjie>go help test usage: go test [build/test flags] [packages] [build/test flags & test binary flags] \'Go test\' automates testing the packages named by the import paths. It prints a summary of the test results in the format: ok archive/tar 0.011s FAIL archive/zip 0.022s ok compress/gzip 0.033s ... followed by detailed output for each failed package. \'Go test\' recompiles each package along with any files with names matching the file pattern "*_test.go". These additional files can contain test functions, benchmark functions, and example functions. See \'go help testfunc\' for more. Each listed package causes the execution of a separate test binary. Files whose names begin with "_" (including "_test.go") or "." are ignored. Test files that declare a package with the suffix "_test" will be compiled as a separate package, and then linked and run with the main test binary. The go tool will ignore a directory named "testdata", making it available to hold ancillary data needed by the tests. As part of building a test binary, go test runs go vet on the package and its test source files to identify significant problems. If go vet finds any problems, go test reports those and does not run the test binary. Only a high-confidence subset of the default go vet checks are used. That subset is: \'atomic\', \'bool\', \'buildtags\', \'nilfunc\', and \'printf\'. You can see the documentation for these and other vet tests via "go doc cmd/vet". To disable the running of go vet, use the -vet=off flag. All test output and summary lines are printed to the go command\'s standard output, even if the test printed them to its own standard error. (The go command\'s standard error is reserved for printing errors building the tests.) Go test runs in two different modes: The first, called local directory mode, occurs when go test is invoked with no package arguments (for example, \'go test\' or \'go test -v\'). In this mode, go test compiles the package sources and tests found in the current directory and then runs the resulting test binary. In this mode, caching (discussed below) is disabled. After the package test finishes, go test prints a summary line showing the test status (\'ok\' or \'FAIL\'), package name, and elapsed time. The second, called package list mode, occurs when go test is invoked with explicit package arguments (for example \'go test math\', \'go test ./...\', and even \'go test .\'). In this mode, go test compiles and tests each of the packages listed on 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 invoked with the -bench or -v flag, go test prints the full output even for passing package tests, in order to display the requested benchmark results or verbose logging. After the package tests for all of the listed packages finish, and their output is printed, go test prints a final \'FAIL\' status if any package test has failed. In package list mode only, go test caches successful package test results to avoid unnecessary repeated running of tests. When the result of a test can be recovered from the cache, go test will redisplay the previous output instead of running the test binary again. When this happens, go test prints \'(cached)\' in place of the elapsed time in the summary line. The rule for a match in the cache is that the run involves the same test binary and the flags on the command line come entirely from a restricted set of \'cacheable\' test flags, defined as -cpu, -list, -parallel, -run, -short, and -v. If a run of go test has any test or non-test flags outside this set, the result is not cached. To disable test caching, use any test flag or argument other than the cacheable flags. The idiomatic way to disable test caching explicitly is to use -count=1. Tests that open files within the package\'s source root (usually $GOPATH) or that consult environment variables only match future runs in which the files and environment variables are unchanged. A cached test result is treated as executing in no time at all, so a successful package test result will be cached and reused regardless of -timeout setting. In addition to the build flags, the flags handled by \'go test\' itself are: -args Pass the remainder of the command line (everything after -args) to the test binary, uninterpreted and unchanged. Because this flag consumes the remainder of the command line, the package list (if present) must appear before this flag. -c Compile the test binary to pkg.test but do not run it (where pkg is the last element of the package\'s import path). The file name can be changed with the -o flag. -exec xprog Run the test binary using xprog. The behavior is the same as in \'go run\'. See \'go help run\' for details. -i Install packages that are dependencies of the test. Do not run the test. -json Convert test output to JSON suitable for automated processing. See \'go doc test2json\' for the encoding details. -o file Compile the test binary to the named file. The test still runs (unless -c or -i is specified). The test binary also accepts flags that control execution of the test; these flags are also accessible by \'go test\'. See \'go help testflag\' for details. For more about build flags, see \'go help build\'. For more about specifying packages, see \'go help packages\'. See also: go build, go vet. C:\Users\yinzhengjie>
3>.使用案例
十三.go tool
1>.go tool 子命令功能概述
它用来运行一些特殊的Go语言工具,直接执行go tool命令,可以看到这些特殊工具。它们有的是其它Go标准命令的底层支持,有的是可以独当一面的利器。
其中有两个指的特别介绍一下,即pprof和trace。
pprof:
用于以交互的方式访问一些性能概要文件。
命令将会分析给定的概要文件,并根据要求提供高可读性的输出信息。
这个工具可以分析概要文件包括CPU概要文件,内存概要文件和程序阻塞概要文件。
这些包含Go程序运行信息的概要文件,可以通过标准代码库代码包runtime和runtime/pprof中的程序来生成。
trace:
用于读取Go程序的踪迹文件,并以图形化的方式展现出来。
它能够让我们深入了解Go程序在运行过程中的内部情况。比如,当前进程中堆的大小及使用情况。再比如,程序的多个goroutine是怎样被调度的,以及它们在某个时可被调度的原因。
Go程序踪迹文件可以通过标准库代码包"runtime/trace"和"net/http/pprof"中的程序来生成。
温馨提示:
上述两个特殊工具对于Go程序调优非常有用,如果想要探究程序运行的过程,或者想要让程序跑的更快,更稳定,那么这两个工具是必知必会的。
另外,这两个工具都收到了go test命令的直接支持,因此你可以很方便的把它们融入到程序测试环境当中。
博主推荐阅读:
https://github.com/GoHackers/go_command_tutorial
2>.查看帮助信息
C:\Users\yinzhengjie>go help tool usage: go tool [-n] command [args...] Tool runs the go tool command identified by the arguments. With no arguments it prints the list of known tools. The -n flag causes tool to print the command that would be executed but not execute it. For more about each tool command, see \'go doc cmd/<command>\'. C:\Users\yinzhengjie> C:\Users\yinzhengjie>
C:\Users\yinzhengjie>go tool pprof usage: Produce output in the specified format. pprof <format> [options] [binary] <source> ... Omit the format to get an interactive shell whose commands can be used to generate various views of a profile pprof [options] [binary] <source> ... Omit the format and provide the "-http" flag to get an interactive web interface at the specified host:port that can be used to navigate through various views of a profile. pprof -http [host]:[port] [options] [binary] <source> ... Details: Output formats (select at most one): -callgrind Outputs a graph in callgrind format -comments Output all profile comments -disasm Output assembly listings annotated with samples -dot Outputs a graph in DOT format -eog Visualize graph through eog -evince Visualize graph through evince -gif Outputs a graph image in GIF format -gv Visualize graph through gv -kcachegrind Visualize report in KCachegrind -list Output annotated source for functions matching regexp -pdf Outputs a graph in PDF format -peek Output callers/callees of functions matching regexp -png Outputs a graph image in PNG format -proto Outputs the profile in compressed protobuf format -ps Outputs a graph in PS format -raw Outputs a text representation of the raw profile -svg Outputs a graph in SVG format -tags Outputs all tags in the profile -text Outputs top entries in text form -top Outputs top entries in text form -topproto Outputs top entries in compressed protobuf format -traces Outputs all profile samples in text form -tree Outputs a text rendering of call graph -web Visualize graph through web browser -weblist Display annotated source in a web browser Options: -call_tree Create a context-sensitive call tree -compact_labels Show minimal headers -divide_by Ratio to divide all samples before visualization -drop_negative Ignore negative differences -edgefraction Hide edges below <f>*total -focus Restricts to samples going through a node matching regexp -hide Skips nodes matching regexp -ignore Skips paths going through any nodes matching regexp -mean Average sample value over first value (count) -nodecount Max number of nodes to show -nodefraction Hide nodes below <f>*total -noinlines Ignore inlines. -normalize Scales profile based on the base profile. -output Output filename for file-based outputs -prune_from Drops any functions below the matched frame. -relative_percentages Show percentages relative to focused subgraph -sample_index Sample value to report (0-based index or name) -show Only show nodes matching regexp -show_from Drops functions above the highest matched frame. -source_path Search path for source files -tagfocus Restricts to samples with tags in range or matched by regexp -taghide Skip tags matching this regexp -tagignore Discard samples with tags in range or matched by regexp -tagshow Only consider tags matching this regexp -trim Honor nodefraction/edgefraction/nodecount defaults -trim_path Path to trim from source paths before search -unit Measurement units to display Option groups (only set one per group): cumulative -cum Sort entries based on cumulative weight -flat Sort entries based on own weight granularity -addresses Aggregate at the address level. -filefunctions Aggregate at the function level. -files Aggregate at the file level. -functions Aggregate at the function level. -lines Aggregate at the source code line level. Source options: -seconds Duration for time-based profile collection -timeout Timeout in seconds for profile collection -buildid Override build id for main binary -add_comment Free-form annotation to add to the profile Displayed on some reports or with pprof -comments -diff_base source Source of base profile for comparison -base source Source of base profile for profile subtraction profile.pb.gz Profile in compressed protobuf format legacy_profile Profile in legacy pprof format http://host/profile URL for profile handler to retrieve -symbolize= Controls source of symbol information none Do not attempt symbolization local Examine only local binaries fastlocal Only get function names from local binaries remote Do not examine local binaries force Force re-symbolization Binary Local path or build id of binary for symbolization -tls_cert TLS client certificate file for fetching profile and symbols -tls_key TLS private key file for fetching profile and symbols -tls_ca TLS CA certs file for fetching profile and symbols Misc options: -http Provide web interface at host:port. Host is optional and \'localhost\' by default. Port is optional and a randomly available port by default. -no_browser Skip opening a browser for the interactive web UI. -tools Search path for object tools Legacy convenience options: -inuse_space Same as -sample_index=inuse_space -inuse_objects Same as -sample_index=inuse_objects -alloc_space Same as -sample_index=alloc_space -alloc_objects Same as -sample_index=alloc_objects -total_delay Same as -sample_index=delay -contentions Same as -sample_index=contentions -mean_delay Same as -mean -sample_index=delay Environment Variables: PPROF_TMPDIR Location for saved profiles (default $HOME/pprof) PPROF_TOOLS Search path for object-level tools PPROF_BINARY_PATH Search path for local binary files default: $HOME/pprof/binaries searches $name, $path, $buildid/$name, $path/$buildid * On Windows, %USERPROFILE% is used instead of $HOME no profile source specified C:\Users\yinzhengjie>
C:\Users\yinzhengjie>go tool trace Usage of \'go tool trace\': Given a trace file produced by \'go test\': go test -trace=trace.out pkg Open a web browser displaying trace: go tool trace [flags] [pkg.test] trace.out Generate a pprof-like profile from the trace: go tool trace -pprof=TYPE [pkg.test] trace.out [pkg.test] argument is required for traces produced by Go 1.6 and below. Go 1.7 does not require the binary argument. Supported profile types are: - net: network blocking profile - sync: synchronization blocking profile - syscall: syscall blocking profile - sched: scheduler latency profile Flags: -http=addr: HTTP service address (e.g., \':6060\') -pprof=type: print a pprof-like profile instead -d: print debug info such as parsed events Note that while the various profiles available when launching \'go tool trace\' work on every browser, the trace viewer itself (the \'view trace\' page) comes from the Chrome/Chromium project and is only actively tested on that browser. C:\Users\yinzhengjie> C:\Users\yinzhengjie>
3>.使用案例
十四.go vet
1>.go vet子命令功能概述
用于检查指定代码包中的Go语言源码,并报告发现可疑代码问题。该命令提供了除编译意外的有一个程序检查方法,可用于找到程序中的潜在错误。
2>.查看帮助信息
C:\Users\yinzhengjie>go help vet usage: go vet [-n] [-x] [-vettool prog] [build flags] [vet flags] [packages] Vet runs the Go vet command on the packages named by the import paths. For more about vet and its flags, see \'go doc cmd/vet\'. For more about specifying packages, see \'go help packages\'. For a list of checkers and their flags, see \'go tool vet help\'. For details of a specific checker such as \'printf\', see \'go tool vet help printf\'. The -n flag prints commands that would be executed. The -x flag prints commands as they are executed. The -vettool=prog flag selects a different analysis tool with alternative or additional checks. For example, the \'shadow\' analyzer can be built and run using these commands: go install golang.org/x/tools/go/analysis/passes/shadow/cmd/shadow go vet -vettool=$(which shadow) The build flags supported by go vet are those that control package resolution and execution, such as -n, -x, -v, -tags, and -toolexec. For more about these flags, see \'go help build\'. See also: go fmt, go fix. C:\Users\yinzhengjie>
3>.使用案例
十五.go version
1>.go version子命令功能概述
用于显示当前安装的Go语言的版本以及计算环境。
2>.查看帮助信息
C:\Users\yinzhengjie>go help version usage: go version [-m] [-v] [file ...] Version prints the build information for Go executables. Go version reports the Go version used to build each of the named executable files. If no files are named on the command line, go version prints its own version information. If a directory is named, go version walks that directory, recursively, looking for recognized Go binaries and reporting 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. The -m flag causes go version to print each executable\'s embedded module version information, when available. In the output, the module information consists of multiple lines following the version line, each indented by a leading tab character. See also: go doc runtime/debug.BuildInfo. C:\Users\yinzhengjie>
3>.使用案例
十六.go命令通用的标记
执行上述命令是,可以通过附加一些额外的标记来定制命令的执行过程。下面是比较通用的标记。
-a:
用于强行重写编译所涉及的Go语言代码包(包括Go语言标准库中的代码包),即使它们已经是最新的了。该标记可以让我们有机会通过改动更底层的代码包来做一些试验。
-n:
使命令仅打印其执行过程中用到的所有命令,而不真正执行它们。如果只想查看或验证命令的执行过程,而不想改变任何东西,使用它正合适。
-race:
用于检测并报告指定Go语言程序中存在的数据竞争问题。当用Go语言编写并发程序时,这是很重要的检测手动之一。
-v:
用于打印命令执行过程中涉及的代码包。这一定包含我们指定的目标代码包,并且有时还会包括该代码直接或间接依赖的那些代码包。这会让你知道哪些代码包被命令行处理过了。
-work:
用于打印命令执行时生成和使用的临时工作目录的名字,且命令执行完成后不删除它。
这个目录下的文件可能会对你有用,也可以从侧面了解命令的执行过程。如果不添加此标记,那么临时工作目录会在命令执行完毕前删除。
-x:
使命令打印其执行过程用到的所有命令,同时执行它们。
温馨提示:
我们可以把这些标记看作命令的特殊参数,它们都可以添加到命令名称和命名的真正参数中间。用于编译,安装,运行和测试Go语言代码包或源码文件的命令都支持它们。