Go a little bit every day, only record in learning, use and confused things, record the essence, not large and complete.

Command go

GOPATH

Go help Gopath.

GOPATH is used to parse import statements.

The GOPATH environment variable is used to indicate where to look for the Go code. On Unix systems, the environment variable is a string separated by:.

If the environment variable is not set, GOPATH defaults to $HOME/go.

GOPATH directory structure

Each directory under GOPATH/ has its own structure specification:

  • The SRC directory holds the source code. The path after SRC/determines either the import path of the package or the name of the compiled executable of the package (taken from the last directory name of the import path).

  • The PKG directory holds the compilation results of the package. Each operating system has its own PKG subdirectory, PKG /GOOS_GOARCH.

    For example: if DIR is a member of the GOPATH environment variable, the import path of the package stored in DIR/ SRC /foo/bar/ is foo/bar. And the compiled result is put into (installed)DIR/ PKG /GOOS_GOARCH/foo/bar.a.

  • The bin directory holds compiled commands. Each command is named after the last element of its source package import path.

    Here’s an example: The source code for the package main command is stored in DIR/ SRC /foo/quux/ (assuming DIR is already in the GOPATH environment variable), its import path is foo/quux, Then this command will be installed in DIR/bin/quux instead of DIR/bin/foo/quux.

    Of course, if the GOBIN environment variable is set, all commands will be installed in this folder. GOBIN must be an absolute path.

Here is an example of a GOPATH directory layout:

    GOPATH=/home/user/go  # GOPATH environment variable/home/user/go/ SRC/foo/ bar/ (Package bar source package) x. goquux/(Package Main source package) y.gobin/quux (Package main installed command/executable file) PKG/linux_amd64/ foo/ bar.a (package bar compiled library)Copy the code

The go command searches all directories in all GOPATH environment variables to find the source files, but the newly downloaded package is placed in the first directory of GOPATH.

GOPATH and Modules

If you use modules(recommended), you no longer use GOPATH to parse import path. In this case, it is used to store:

  • Download thepackageThe source code will be stored inGOPATH/pkg/mod/Directory.
  • The compiled command will be installed toGOPATH/bin/directory

Internal directoryinternal directories

Here is a description of pacakge’s reference rules.

Assuming the current directory is called internal, packages in the internal/subdirectory can only be used by code imports in its parent directory.

The directory structure is as follows:

    /home/user/go/
        src/
            crash/
                bang/              (go code in package bang)
                    b.go
            foo/                   (go code in package foo)
                f.go
                bar/               (go code in package bar)
                    x.go
                internal/
                    baz/           (go code in package baz)
                        z.go
                quux/              (go code in package main)
                    y.go
Copy the code

The import path of z.geo is foo/internal/baz, but this import statement can only appear in the source file of foo’s directory tree. For example, foo/ f.co, foo/bar/x. co, and foo/quux/ y.co can all use the import statement import foo/internal/baz. However, the source file crash/bang/ b.globe cannot be used.

Vendor Directories

Use less, do not translate. If you are interested, check out the corresponding section of Go Help Gopath.


import path

Go help importpath

An import path is used to represent a package stored in the local file system. That is, the importPath of each package is unique

In general, an import path represents either a standard library package (e.g., Unicode/UTF8) or a package in the workspace (see Go Path above).

Relative import pathrelative import paths

If an import is followed by a path with./.. /, indicating that this is a relative path.

The go command supports realtive import path as an abbreviation of import path. There are two forms:

    1. relative pathinThe command lineAs in theimport pathThe shorthand.

    If the import path of pacakge in your folder is Unicode, then to test unicode/ UTf8 packages, you can write: go test./urf8.

    In addition to. /,.. /, in relative paths, we also use pattern matching…. E.g. Go test./… , the go command tests all packages under the current directory (including the subdirectories of each level).

    1. nonworkspace(GOPATH/src GOPATH/bin) under the circumstances,relative pathCan be found inIn the programuse

    If you are compiling a Go program that is not under workspace, you can use relative Path in the program to import a “near” package (nearby packages cannot be under workspace either).

    This makes it easy to use programs made up of multiple packages outside of the workspace. But there is no way to go install such programs, because there is no place to install them (not in the workspace, and not a Module). So every time you build, you start from scratch.

    To avoid ambiguity, the GO program does not allow relative Import Path to be used within the Workspace workspace. Only the full import path can be used.

Remote import pathremote import path

Some import paths also describe how to get the source code for the package using a version control system such as Git.

Here’s github as an example:

GitHub (Git)

          import "github.com/user/project"
          import "github.com/user/project/sub/directory"
Copy the code

To represent the location of the code, the import path needs to specify which repository and the code path within the repository.

repository.vsc/path   # VCS suffix can be omitted (version contorl system)
Copy the code

Git as an example:

Import “example.org/repo.git/foo/bar” indicates that the root directory in the git repository example.org/repo/ pacakge, path is foo/bar/warehouse.

When using GOPATH, downloaded packages are written to the first directory of the GOPATH environment variable (go help GOPATH -get).

When modules is used, the downloaded package is written to the module cache (go help module-get).

packages && import path

Package lists and patterns

Go commands, most of which take the form: go command [packages]. Typically [packages] is a list of import paths.

The first thing we need to know is that we usually use the import path import path to identify a package. So we first need to figure out what the import path of the package is.

Given an import path, we need to parse it first (through file System/GOPATH/ mdoules), and the resolved directory is the directory where pacakge code is stored.

Local packageimport path

Import path can be resolved in two ways:

  • Case1: Resolve import path through local file system

    An import path is found through the file system path in two cases:

    • An absolute pathrooted path( /xxx/ooo )Only applicable to the command line, procedures can not use absolute path!
    • Or to. .The leading relative path applies only to notworkspaceIn the case
  • Case2: Resolve import path through GOPATH (see section above: GOPATH)

    $GOPATH/ SRC /

    does not match the import path of case1.

If import path is not specified in the go command, the action will be applied to pacakge in the current directory.

The pattern model

If the import path contains one or more… Wildcard, then the import path is a pattern. Each wildcard can match strings (including “/” and empty strings). This pattern looks for all package directories that match the pattern under the $GOPATH directory tree.

There are two special cases to know about wildcards:

  • case1: /...Appear in thepatternFinally, can matchAn empty stringSo the patternnet/...Can matchnet, can also match in its subdirectoriespackages, such asnet/http.
  • Case2: indicates the value of the/The split element, if a wildcard., then the wildcard will not matchvendorGraphics.. /...It doesn’t match./vendorOr,./mycode/vendor.

Distal packageimport path

An import path can also be named a package that needs to be downloaded from a remote repository (see section “Import Path” above).


Each package in the program must have a unique import path. By convention, import path has a unique prefix. For example, at Google, the import path used internally starts with Google, while the import path of the packages in the remote repository is prefixed with the path of the packages in the remote repository, such as github.com/user/repo.

Package names for packages in the program do not need to be unique (because we identify packages by import path). However, there are two reserved package names: package main and package documentation. Package main indicates that the current package is a command, not a library file. The command packages are compiled into executable files. Files in package Documentation are ignored by the GO command.

There is a special case if [packages] is a list of.go files in the same folder. The go command is applied to the package consisting of these files (all other files in the directory are ignored).

Files or directories starting with., _ are ignored by the go command. Directories named testData are also ignored.


.goIn the source filepackage import:

If you need to import another package from the source file, what should you do? Here is a brief summary, specifically look at the following article:

Package&&Module (Package&&Module

  • In the absence of modules (outside the scope of modules), the import path of the package is

    • $GOROOT/src/subdirectory path to package
    • or$GOPATH/src/subdirectory path to package
    • Or is itRelative paths
  • In the case of modules, the import path of the package is

    • module path/subdirectory path to pacakge

go build

The premise is that the build command builds in pacakge units.

Build compiles the package specified by import path on the command line with its dependencies, but does not install it (in the specified directory).

Build parameter type

  • When the go build command is executed without any arguments, the command will attempt to compile the package corresponding to the current directory.

  • The build argument is a list of. Go files in a folder

    If the build command takes a list of. Go files in the same folder, the build command will assume that these source files constitute a package. And when compiling this package, the build command ignores files ending in _test.go.

    Note: The list of.go files must all be in the same folder, which makes sense because Build thinks they constitute a package and different folders are different packages.

  • The build argument is the import path of a package

  • Build arguments are import paths for packages

Build results/outputs

There is output

When the build command compiles a single main package, the build command produces an executable file named in two ways:

  • If the build parameter is.goList of files, then the executable file will beFirst in the list of filesSource file naming (go build ed.go rx.goWill produce oneedExecutable file).
  • If the build argument is onepackagetheimport path, will be inimport pathIs named by the directory in which the package resides (go build unix/sam, outputsamExecutable file).

There’s no output

If the build command compiles multiple packages(specifying multiple import paths), or builds a non-main pacakge, the build command compiles these pacakges, but dismisses the output and simply tests whether the packages can be compiled.

-o: writes the compilation result to the specified file/directory

When the -o parameter is present, the compilation result is forced to remain.

  • -o specifies a fileName named fileName

    Write the compilation results of a single package to this file. Regardless of whether the package is main or not, the compiled results are written to this file.

    go build -o fileName  import_path
    go build -o fileName  x.go x2.go.Copy the code

    The build command generates a fileName file.

  • -o Specifies a folder directory

Place the compiled executable file in directory.

Note that the directory must exist, otherwise an error will be reported (as a filename)

go build -o direcory import_path1 import_path2 ....
Copy the code

Executables generated by compiled Pacakge will be placed under directory/.

Common build arguments (common to clean, get, install, list, run, test commands)

  • -v: in the buildpackagePrint out the names of the packages.
  • -work: Prints temporary working directories without deleting them at the end of compilation.

go install

The go install command is used to compile and install specified code packages and their dependencies. This command handles dependencies for the specified code package if they have not been compiled and installed.

In fact, the go install command does only one more thing than the go build command: install the compiled result file into the specified directory.

Internally, this command is split into two steps: the first step is to generate the compiled result file (executable or.a static linked library file), and the second step moves the compiled result to GOPATH/ PKG or GOPATH/ PKG or GOPATH/ PKG or GOPATH/bin.

  • Case1: If a program belongs topackage main(This package is executable), then when executedgo install <import path>It will generate itBinary fileAnd put it$GOPATH/bin/Directory.
  • Case2: if a program belongs topackage mainOther than the other packages, then when executedgo install <import path>When, will be in$GOPATH/pkgDirectory create aStatically linked library.aFile.

go get

The go get command downloads or updates the required dependencies (modules), compiles and installs them.

Update/install dependencies are written to the current Moduel go.mod file.

Internally, this command actually breaks down into two steps:

  • Step1: the first step is to determine which dependencies to add and the versions of those dependencies.

    Go get xxxx@version You can specify the module version to obtain with @version. If @version is not specified, the default installation/update depends on the @latest version.

    go get github.com/username/repo-name # @ latest by default
    
    # specify module version (by version number/branch name /commitID)Go get golang.org/x/[email protected] go get golang.org/x/text@masterCopy the code

    Note: Although the go get command installs/updates the module that provides the package to the @latest version, it does not install/update the module that depends on it to the latest version.

    Too convoluted, for example:

    If the latest version of Module A requires Module B v1.2.3 and Module B has several versions of V1.2.4 and v1.3.1 available, go Get A will install/update the latest version of A. However, version B v1.2.3 on which A depends will be installed/updated.

    The -u argument, if added to go get -u, will cause the get command to update the module that the package depends on on the supply command line to @latest version (the latest minor/modified version).

    This sentence is difficult to translate in Chinese: The -u flag instructs get to update modules providing dependencies of packages named on the command line to use newer minor or patch releases when available.

    If the command go get -u A, the latest version of A will be used, and the v1.3.1 version of B will be used (not B v1.2.3). But if B depends on Module C, and C does not provide any package in A’s build (except _test.go, because the test file is not compiled), then C will not be updated to the latest version.

    The downloaded package will be placed under $GOPATH/ SRC/and referenced as follows:

    import "github.com/username/repo-name"
    Copy the code
  • Step2: The second step is to download/compile/install these packages.

    If the argument on the command line is a module rather than a package(in the case of a module without a go source file at its root), install will not be executed.


Reference link – Go compilation and tools

go install

Go a get command

Go Command Tutorial