GOROOT: The path to the Go language installation root directory, which is also the Go language installation path. GOPATH: Path to several workspace directories. It’s a workspace that we define ourselves. Very important before the Go Module mode, it is now basically used to hold items obtained using the Go Get command. GOBIN: Go Installation directory of the generated program. For example, run the Go install command to save the generated Go program to this directory for terminal use.

1. GOROOT installation directory description

The value of GOROOT is the Go installation directory. The installation directory is as follows:

wohu@wohu:/usr/local/go$ ls
api      bin              CONTRIBUTORS  favicon.ico  LICENSE  PATENTS  README.md   src   VERSION
AUTHORS  CONTRIBUTING.md  doc           lib          misc     pkg      robots.txt  test
wohu@wohu:/usr/local/go$
Copy the code
directory instructions
api Used to store a list of API deltas in Go version order. The API in question contains exposed variables, constants, functions, and so on
bin Used to store major standard command files, including go, GOdoc, and GOfmt
doc Program documents used to store the standard library in HTML format. We can use the godoc command to launch a Web application to present these documents
lib Used to store some special library files
misc Instructions and tools for storing some helper classes
pkg Used to store all archive files for installing the Go standard library
src Used to store Go itself, Go standard tools and standard library all source files
test Store all relevant files used to test and verify the Go itself
  • PKG directory:
wohu@wohu:/usr/local/go$ ls pkg/
include  linux_amd64  linux_amd64_race  tool
Copy the code

You’ll find a folder named Linux_AMd64, which we call the platform dependent directory. The names of these folders are a combination of the names of the corresponding operating system and computing architecture.

With the go install command, the Go program (in this case, the standard library program) is compiled into a platform-specific archive and stored there. In addition, the PKG /tool/ Linux_amd64 folder contains many powerful commands and tools used to create software using Go.

wohu@wohu:/usr/local/go$ ls pkg/linux_amd64
archive    context.a  encoding    fmt.a   html.a    io     math.a  os        reflect.a  sort.a     syscall.a  unicode
bufio.a    crypto     encoding.a  go      image     io.a   mime    os.a      regexp     strconv.a  testing    unicode.a
bytes.a    crypto.a   errors.a    hash    image.a   log    mime.a  path      regexp.a   strings.a  testing.a
compress   database   expvar.a    hash.a  index     log.a  net     path.a    runtime    sync       text
container  debug      flag.a      html    internal  math   net.a   plugin.a  runtime.a  sync.a     time.a
wohu@wohu:/usr/local/go$
Copy the code

2. Description of GOPATH working interval

GOPATH is working on the interval for his own project, which we have set up in note learning (1). You can see all of the environment variables of GO using the Go env.

wohu@wohu:~/gocode$ go env
GOARCH="amd64"
GOBIN="/home/wohu/gocode/bin"
GOCACHE="/home/wohu/.cache/go-build"
GOEXE=""
GOFLAGS=""
GOHOSTARCH="amd64"
GOHOSTOS="linux"
GOOS="linux"
GOPATH="/home/wohu/gocode"
GOPROXY=""
GORACE=""
GOROOT="/usr/local/go"
GOTMPDIR=""
GOTOOLDIR="/usr/local/go/pkg/tool/linux_amd64"
GCCGO="gccgo"
CC="gcc"
CXX="g++"
CGO_ENABLED="1"
GOMOD=""
CGO_CFLAGS="-g -O2"
CGO_CPPFLAGS=""
CGO_CXXFLAGS="-g -O2"
CGO_FFLAGS="-g -O2"
CGO_LDFLAGS="-g -O2"
PKG_CONFIG="pkg-config"
GOGCCFLAGS="-fPIC -m64 -pthread -fmessage-length=0 -fdebug-prefix-map=/tmp/go-build076028171=/tmp/go-build -gno-record-gcc-switches"
Copy the code

GOPATH is used as a search path for compiled binaries and import packages (actually your working directory, you can create your own Go source files under SRC and start working). In general, Go source files must be stored in the workspace.

GOPATH contains three directories: bin, PKG, and SRC

wohu@wohu:~/gocode$ echo $GOPATH
/home/wohu/gocode
wohu@wohu:~/gocode$ ls
bin  pkg  src
wohu@wohu:~/gocode$
Copy the code

We need to add the workspace directory path to the environment variable GOPATH. Otherwise, even if you are in the same workspace (in fact, directories that are not added to GOPATH do not need to be workspaces), you cannot call each other through the absolute code package path.

In a real development environment, there can be only one or multiple workspaces, and the directory paths of these workspaces need to be added to GOPATH. As with GOROOT, we should make sure GOPATH is always working.

GOPATH="/home/wohu/gocode"
Copy the code

GOPATH, described in many books and articles on the Go language, is implemented by modifying global environment variables of the system. However, this approach to setting up the global GOPATH can cause the current project to misreference the Go source file in another directory, resulting in the wrong version of the compile output, or the compile to report some unintelligible error message.

For example, save some project code in /home/davy/projecta and set the directory to GOPATH. As development proceeds, it is necessary to obtain a copy of the project’s source code again, which is stored in the /home/davy/projectb directory. If the project needs to be compiled in the projectB directory, the developer forgets to set GOPATH and uses the command line instead. The current GOPATH points to the /home/davy/projecta directory, not the projectB directory the developer expected at compile time. When the compilation is complete, the developer releases the faulty project version to the Internet.

Therefore, it is recommended that you do not set GOPATH globally when compiling the Go source, whether from the command line or using an integrated development environment. Instead, you set GOPATH with your project.

GOPATH means: You can think of GOPATH simply as the Go language’s working directory. The value of GOPATH is the path to a directory or multiple directory paths, each representing a workspace for the Go language.

We need to facilitate these workspaces to place source files for the Go language, archive files (i.e., files with.a extensions) and executable files after install.

Under Linux, archive files are files with an extension of. A, also known as archive files. Friends who have written C programs know that this is a static library file generated after the program is compiled.

In what order does the Go language find dependency packages in multiple workspaces? Answer: GOROOT and then GOPATH.

wohu@ubuntu-dev:~/project/go/src/github.com$ go install github.com/ramya-rao-a/go-outline
can't load package: package github.com/ramya-rao-a/go-outline: cannot find package "github.com/ramya-rao-a/go-outline" in any of:
        /usr/local/go/src/github.com/ramya-rao-a/go-outline (from $GOROOT)
        /home/wohu/project/go/src/github.com/ramya-rao-a/go-outline (from $GOPATH)
Copy the code

Will there be conflicts if there are code packages with the same import path in multiple workspaces? The answer is: no conflict. Because Go looks for code packages sequentially. For workspaces in GOPATH, it looks them up in the order you set them up. So it finds and uses the same path project in the earlier workspace.

2.1 the SRC directory

  • srcDirectory: Mainly storesGoSource code file

Organize and save Go source files in code packages that correspond to the SRC subdirectory. For example, if a source file is declared to belong to the code package log, it should be stored in the “SRC /log” directory. Of course, you can also place the Go source files directly in the SRC directory, but such Go source files can only be declared as part of the main package.

Unless used for temporary testing or demonstrations, it is generally recommended to store the Go source files in a specific code package.

2.2 PKG directory

  • pkgDirectory: store compiled library files, mainly.afile

Archive file used to store code packages installed by the go install command. The premise is that the code package must include the Go library source file. Archive files are those whose names end in.a.

This directory functions similarly to the PKG directory in the GOROOT directory. The difference is that the PKG directory in the workspace is dedicated to archiving user code.

Compiling and installing user code is typically done on a package basis. For example, after the log package is compiled and installed, an archive file named log.a is generated and stored in a platform-specific directory under the PKG directory of the current workspace.

The. A file belongs to the static link library file, which is a program in a code package. The Go language’s linker can link related static libraries together to produce the final executable. When the Go language installs executables, it packages the associated statically linked libraries with them. So the generated executable can run independently, which is also an obvious advantage.

2.3 bin directory

  • binDirectory: Stores executable files

Similar to the PKG directory, the executable generated from the go command source file is saved after the installation is completed using the go install command. On Unix-like operating systems, this executable file is generally named the same as the main file name of the source file.

On Windows, the name of the executable file is an. Exe suffix added to the main file name of the source file.

You need to configure the executable directory bin in GOPATH into the environment variable as well, otherwise the self-downloaded third-party go tool will not be available.

GOBIN="/home/wohu/gocode/bin"
Copy the code

Note: Do not include the Go language installation directory in GOPATH to keep the Go language workspace strictly separate from the user workspace. With the Go get code grab command in the Go tool, you can specify that the code for your project is downloaded to the first workspace we set up in GOPATH, where compilation and installation can be completed.

The files in the three directories are as follows:

wohu@wohu:~/gocode$ ls bin/
dlv  gocode  godef  golint  go-outline  gopkgs  goplay  gorename  goreturns  go-symbols  guru  impl
wohu@wohu:~/gocode$ ls pkg/
linux_amd64  mod
wohu@wohu:~/gocode$ ls src/
github.com  golang.org  hello  hello.go
Copy the code
  1. Go language source code organization

A package can contain any number of source files with the.go extension, all of which need to be declared to belong to the same package.

The Go source code is organized around environment variables GOPATH, workspaces, SRC directories and code packages. In general, the Go source files need to be stored in a code package in the SRC directory of one of the workspaces contained in the environment variable GOPATH.

  1. Understand the results of the source code installation

The source files are usually placed in the SRC subdirectory of a workspace. If an archive file (with the.a extension) is generated after installation, it will be placed in the PKG subdirectory of that workspace; If an executable is generated, it might be put into the bin subdirectory of that workspace.

  1. Understand the process of building and installing the Go program

Build using the go build command, install using the go install command. Compilation, packaging, and so on are performed when code packages are built and installed, and any files generated by these operations are first saved to a temporary directory.

If you are building a library source file, the resulting file will only exist in the temporary directory. The main point of the build here is to check and validate.

If you build a command source file, the resulting operation file is moved to the same directory as the source file.

The install operation performs the build first, then links, and moves the resulting file to the specified directory. And going further,

  • If a library source file is installed, the resulting file is moved to its workspacepkgIn a subdirectory of the directory.
  • If the command source file is installed, the resulting file is moved to its workspacebinDirectory, or environment variablesGOBINIn the directory pointing to.

3. Source file

Go source files are divided into three kinds, that is, command source file, library source file and test source file. All source files in the same directory must have the same package name, no matter whether they are command source files or library source files.

Build = compile + link

  1. Compiling and linking are two steps.
  2. After a code package has been installed (compiled, linked, and generated), the corresponding static link library file is loadedgoTools inpkgIn the directory.
  3. At compile time, ifpkgThe directory already has a static link library file that depends on the code package, so by defaultgoThe tool will not compile again.
  4. At link time, if the static link library file that depends on the package already existspkgIt’s in the catalog, sogoTools will be used directly. The process of linking is essentially linking the main and dependent packages together.

Part of what makes Go so convenient is the way its tools manage statically linked libraries.

3.1 Command source file

Declared as part of the main package and containing the source file for the main function that has no argument declarations and no result declarations. This type of source code is an entry point into the program and can be run independently (using the go run command) or converted into an executable by the Go build or Go install command.

All source files in the same package must have the same package name. If the command source file and the library source file are in the same code package, the package will not execute the go build and Go install commands correctly. In other words, these source files cannot be compiled and installed. Therefore, command source files are usually placed in a separate code package. Typically, a program module or software has only one startup entry.

You can have multiple command source files in the same code package and run them separately with the Go run command. However, the go build and go install commands cannot compile and install the code package. Therefore, in general, it is not recommended to put multiple command source files in the same code package.

If only one command source file exists in the code package, run the go build command in the directory where the file resides to generate an executable file with the same name as the directory. If you use the go install command, you can generate the corresponding executable file in the bin directory of the current workspace.

Conclusion: If oneGoThe source file is declared to belong tomainPackage, and the file containsmainFunction, which is the command source file. The command source file belongs to the entry of the program and can be passedGoThe language of thego run The command is executed or passedgo build Command to generate an executable file.

3.2 Library source files

A library source file is a normal source file that exists in a package and does not contain the **main** function. The package name declared in the library source file is the same as the name of the package (directory) to which it actually belongs, and the library source file does not contain the main function with no parameter declaration and no result declaration.

For example, if you run the go install command in the basic/set directory, the basic/set package is successfully installed and an archive file named set.a is generated. The directory for storing archive files is generated by the following rules:

  • The archive generated when the library source files are installed is placed in the PKG directory of the current workspace.
  • The archive files are placed in platform-specific directories under the PKG directory, depending on the target computer architecture being compiled. Set. A is in the PKG/Windows_amd64 directory on a 64-bit Windows system.
  • The relative path of the directory where the archive is stored is the same as the relative path of the code package above the installed code package.

The first relative path is relative to the platform-specific directory in the workspace PKG directory, and the second relative path is relative to the workspace SRC directory. If the installed package does not have an upper-level package (that is, its parent directory is the working SRC directory), its archive files are placed directly in the platform-specific directory of the PKG directory of the current workspace. For example, the basic archive file basic.a will always be directly stored in the PKG /windows_amd64 directory, and the basic/ SET archive file set.a will be stored in the PKG /windows_amd64/basic directory.

3.3 Test the source file

This is a special library file that runs all the test source files under the current code package by executing the go test command. There are two sufficient conditions to be a test source file:

  • The file name must end with _test.go
  • The file must contain at least one function with a name starting with Test or Benchmark and one parameter of type * testing.t or testing.b. The types testing.t or testing.b are two structure types.

When you run the go test command in a code package, all the test source files in that code package are found and run.

Note: The text file that stores the Go code needs to be stored in UTF-8 encoding. If a non-UTF-8 encoded character appears in the source file, Go will throw the “illegal UTF-8 sequence” error when running, compiling, or installing.

Code examples:

wohu@wohu:~/GoCode/ SRC $├── ├─ download │ ├── download │ ├── upload │ ├── download │ ├── download │ ├── download │ ├── upload │ ├── download │ ├── download │ ├── upload │Copy the code

Download_demo. go

package download

import "fmt"
// The Download_imge method name starts with a capital letter, which means it can be called externally
func Download_imge(a) {
	fmt.Println("This is download image demo")}Copy the code

Upload_demo. Go

package upload

import "fmt"
// Upload_imge method name starts with a capital letter, indicating that external can be called
func Upload_imge(a) {
	fmt.Println("This is upload image demo")}Copy the code

Main. go code contents:

package main

import (
	"download"
	"upload"
)

func main(a) {
	upload.Upload_imge()
	download.Download_imge()
}
Copy the code

Run the go run, go build, and go install commands respectively, and you can see that the output is normal, the binary file main is generated, and the corresponding binary file is found in the bin directory.

wohu@wohu:~/GoCode/src$ go run main.go This is upload image demo This is download image demo wohu@wohu:~/GoCode/src$ ls download main.go upload wohu@wohu:~/GoCode/src$ go build main.go wohu@wohu:~/GoCode/src$ ls download main main.go upload  wohu@wohu:~/GoCode/src$ ./main This is upload image demo This is download image demo wohu@wohu:~/GoCode/src$ go install  main.go wohu@wohu:~/GoCode/src$ ls .. /bin/ main wohu@wohu:~/GoCode/src$ ls .. /pkg/ wohu@wohu:~/GoCode/src$Copy the code

4. Brief description of standard commands

Go itself contains a number of commands and tools for working with Go programs.

4.1 Common Commands

  • build

Used to compile specified code packages or Go language source files. The command source file is compiled into an executable file and stored in the command execution directory or a specified directory. After the library source files are compiled, no files are left in the non-temporary directory.

  • clean

Use to clean up temporary directories and files left over from other go commands.

  • doc

Used to display documents that print Go language code packages and program entities.

  • env

This command is used to print environment information about the Go language.

  • fix

Fixes outdated syntax and code calls contained in source files for specified code. This makes it very easy to synchronize updates when upgrading the Go language version.

  • fmt

Use to format the Go source file in the specified code package. In fact, it does this by executing the gofmt command.

  • generate

Identifies the “Go :generate” annotation in the resource file in the specified code and executes any command it carries. This command is independent of the Go standard compilation and installation system. If you have a “Go :generate” comment that you need to parse, run it alone. This command is very useful, and I often use it to automatically generate or modify the Go source files.

  • get

Used to download, compile, and install specified change packages and their dependencies. It’s all up to us to automatically pull code from our own code repository or third-party code base.

  • install

Use to compile and install the specified code package and its dependencies. After installing the command source files, the corresponding executable files are generated in the bin subdirectory of the workspace directory where the code package resides, or in the directory pointed to by the current environment variable GOBIN. After the source files are installed, an archive is generated in the PKG subdirectory of the working directory where the code package resides.

  • list

Displays information about a given code package, a handy tool for code package analysis. Using the template syntax specified in the Go standard code base package “Text/Template”, you can control the output with great flexibility.

  • run

Use to compile and run the specified source code file. This is needed when you want to run command source files without generating an executable.

  • test

Use to test the specified code package, provided that the test source file must exist in the code package directory.

  • tool

Special tools for running the Go language.

  • vet

If the developer has already written some code, vet helps the developer detect common errors in the code. Let’s take a look at what types of errors VET catches.

  • The Printf class function was called with a type matching an incorrect argument.
  • Error in method signature while defining common methods.
  • Incorrect structure tag.
  • Structure literals that do not specify field names.

Use to examine the Go language code in the specified code package and report suspicious code problems found. This command provides another method of program inspection in addition to compilation, which can be used to find potential errors in the program.

go vet main.go
Copy the code
  • version

Displays the version information and computing environment of the currently installed Go language.

4.2 Additional Parameters

When executing the above command, you can customize the execution of the command by attaching some additional tags. Here is a more general tag.

  • -n

Causes a command to print only all the commands used in its execution, without actually executing them. If you just want to see or verify the execution of a command and don’t want to change anything, use it.

  • -race

Used to detect and report data contention problems in specified Go language programs. This is one of the most important checks when writing concurrent programs in Go.

  • -v

This command is used to print code packages involved in command execution. This must include the object code package that we specify, and sometimes those that the code package depends on directly or indirectly. This will let you know which code packages are being processed by the command.

  • -work

Print the name of the temporary working directory that is generated and used during command execution and is not deleted after command execution is complete. The files in this directory may be useful to you, as well as give you a side view of the command execution process. If this flag is not added, the temporary working directory will be deleted before the command completes.

  • – x:

Causes the command to print all the commands used in its execution and execute them simultaneously.

We can think of these tags as special arguments to a command that can be added between the command name and the actual arguments to the command. They are supported by commands used to compile, install, run, and test Go language code packages or source files. The tool subcommand mentioned above is used to run some special Go language tools. You can see these special tools by executing the go tool command directly. Some of them are low-level support for other Go standard commands, and some of the rules are powerful tools that can stand on their own. Two of these tools deserve special mention.

  • pprof

Use to interactively access some performance profiles. The command will analyze the given profile and provide highly readable output information on request. The profiles that the tool can analyze include CPU profiles, memory profiles, and program blocking profiles. These profiles, which contain information about the run of the Go program, can be generated by programs in the library code Runtime and Runtime /pprof.

  • trace

It is used to read the Go program trace file and show it in a graphical way. It gives us an inside look at the Go program as it runs. For example, the size and usage of the heap in the current process. For example, how multiple Goruntimes in a program are scheduled and why they are scheduled at any given moment. Go program trace files can be generated by programs in the standard code package “Runtime/Trace” and “NET/HTTP /pprof”.

The two special tools mentioned above are very useful for tuning Go programs. If you want to explore the process of running a program, or want to make the program run faster and more stable, then these two tools are a must. In addition, both tools are directly supported by the Go test command. So you can easily incorporate them into your application testing.