This is a creation in Article, where the information may have evolved or changed.
Standard library-operation source Collection Go Package info: go/build
In the Golang standard library, there are a class of packages that are used to process go project directory structure, source code, syntax, basic operations, and so on. General procedures may not use these packages, but in the Go tool chain source used, the reason to learn these standards library, is to better see the source of the Go tool chain. First, let's look at the library that collects the Go package information: Go/build
First, Build Package overview
The package document first describes the go Path. If this section is unclear, you can look at the documentation, or other official documents, or look at the directory structure of the GO project.
If you have seen go source, you should have seen a package like this note: +build ignore. This is a compilation constraint (build Constraints), which can be understood as conditional compilation. More on this section, more on this later.
Ii. Types and functions
1. Tooldir variable
var tooldir = filepath. Join (runtime. Goroot (), "pkg/tool/" +runtime. Goos+ "_" +runtime. Goarch)
The value of the variable is the path to the Go tool chain. Tools like 6g/6l, right under this path.
2. Archchar function
Gets the character representation of the schema. Described in the previous article. For example: x86 32bit with 8, AMD64 with 6 and so on. The function obtains the corresponding schema character by passing in the Goarch. such as: Build. Archchar (runtime. Goarch)
3. Islocalimport function
Determines whether it is "local import", similar to ".", ".", "./foo" or ". /foo ". Formal projects, generally not recommended for local import, using local import many people will say that the package is not found.
4. Type of context
The type specifies the context environment for the build (build). For example: Current operating system, architecture, go root directory, Gopath, etc.
This type provides a function member in addition to the variable member, and if the function member is nil, the function provided by the other library is used.
5. Package Type
Description Go Pack
Iii. main types of methods (including instantiation)
1, the context of the instantiation and method
var Default Context = Defaultcontext ()
This is the default implementation, which is the default implementation used by the go build tool. Default uses the Goarch, GOOS, goroot, and Gopath environment variables and, if not set, uses the values from the installation runtime.
1) Import method
Func (Ctxt *context) Import (path string, srcdir string, Mode Importmode) (*package, error)
Imports a package that returns a bundle type pointer. The path parameter is the same as the path of the import path in your code. Srcdir is the path to the source code, while the Importmode type provides two types in the build package: Findonly and Allowbinary. Allowbinary can be used when the package source code does not exist, the compiled package object file is directly referenced.
Before, in the forum (about the code organization of Go) discussed such a problem: go build, if the dependent package source code does not exist, the compilation is unsuccessful, there is a solution to the Go tool 6g this way to compile. Now, after you know the allowbinary parameter, you should be able to fix the problem by modifying the Go Tool source code. In Pkg.go in the Src/cmd/go directory, 225 has this code:
?
www.usr.cc
| 123 |
//TODO:After Go 1, decide when topass build.AllowBinary here.// See issue3268 for mistakes to avoid.bp, err := buildContext.Import(path,srcDir,0) |
By looking at the source of the import, you can know the details of the package installation, such as where to install.
When the directory does not contain the source code, if an error occurs, a nogoerror error is returned.
In addition, the build package provides an easy way to import a method, namely: Import function, default call to the import method of default
2) Importdir Method
Internal implementation: Return Ctxt. Import (".", dir, mode)
3) Srcdirs method
Lists the source directories in Goroot and Gopath. For example, I did not set Gopath, and the result is as follows:
Fmt. Println (build. Default.srcdirs ())//[c:\Go\src\pkg]
2, the package of the instantiation and method
The import and Importdir of the context will return to the package instance (*package), and of course, it can be instantiated directly.
The package provides a way to determine if a bundle is a command, that is, whether it is a main packet
Func (P *package) Iscommand () bool
3. Fields for context and package
Because of the large number of these two types of fields, each field in the package document has comments, which are not explained here.
Iv. Building constraints (build constraints)
or conditional compilation (compile condition)
1. Instructions for use
In Go source (src/pkg or src/cmd) search +build, found that there are many files at the beginning of such comments
+build xxx
A build constraint is a one-line comment that starts with +build. Some conditions are listed after +build, when this condition is established, the file should be included in the package (that is, it should be compiled into the package file), the constraint can appear in any source file, that is, not limited to the go source file. However, these conditions must be at the top of the file (just before the code, that is, there can be other comments before +build), after the +build comment, there should be a blank line (this is to be separated from the package Doc area).
Syntax rules:
1) only allowed is alphanumeric or _
2) between multiple conditions, a space represents an or, a comma denotes an and, an exclamation mark (!) Represents not
3) A file can have multiple +build, and the relationship between them is and. Such as:
+build Linux Darwin
+build 386
Equivalent to
+build (Linux OR Darwin) and 386
4) Pre-defined conditions:
Runtime. GOOS, runtime. Goarch, compiler (GC or GCCGO), CGO, context. Other words in the Buildtags
5) If a file name (without suffixes) is terminated with *_goos, *_goarch, or *_goos_goarch, they implicitly contain the build constraint
6) When you do not want to compile a file, you can add//+build ignore. Ignore here can be other words, just ignore more people know what meaning
For more details, you can view the Shouldbuild and match methods in the Go/build/build.go file.
2. Application examples
In addition to this pre-defined application of *_goos, we look at a practical application.
For example, the project needs to output DEBUG information in the test environment, usually through a variable (or constant) to control whether it is a test environment or a production environment, such as: if DEBUG {}, so that in the production environment each time the same judgment. Someone asked such a question in the Golang-nuts mailing list, seemingly without a better approach (want to have the same effect as conditional compilation in C). Below we use build constraints to implement.
1) file list: Main.go logger_debug.go logger_product.go
2) Simply call the Debug () method in the Main.go.
3) Debug () in Logger_product.go is an empty implementation, but at the beginning of the file Add//+ build!debug
4) Debug in Logger_debug.go () is required to output debugging information, at the same time at the beginning of the file Plus//+ build Debug
In this way, the-tags parameter is passed when the test environment is compiled: Go build/install-tags "Debug" logger. Production environment: Go Build/install logger on the line.
Why would you compile logger_product.go for a production environment without passing-tags? Because there is a sentence in the match method in Go/build/build.go:
1 if strings. Hasprefix (name, "!") {//Negation
2 return len (name) > 1 &&!ctxt.match (name[1:])
3}
That is, as long as there is! (not just!), tag is always compiled when it is not in buildtags.
Full source on GitHub