Go lang uses a conceptual element, package, to pool code. Callability of all code functions is defined at the package level. If we need to invoke dependencies, then "import" is fine, internal or external, using the import keyword. But things are often not that simple. Go lang has taken a lot of detours in the package management mechanism. Although version 1.1 8 of package management has become mature, we still need to know this history.
environment variable
In general, go lang relies on two environment variables in the system: GOPATH and GOROOT, which are a bit like the concept of Python's interpreter directory. GOROOT is used to tell the currently running Go process the current Go installation path and where to look for GoSDK-related classes when it runs.
The GOPATH variable is set to default that all projects and referenced third-party packages are downloaded to the src directory of GOPATH, that is, your code cannot be compiled as long as it is not in GOPATH. We can understand that this directory is the project directory, which is quite different from Python, whose pip package management mechanism is still a classic package-dependent design pattern.
GOPATH can cause a lot of problems. For example, I have many go lang projects, and each project has its own GOPATH directory. All dependent packages are in the project's own directory, which leads to too many duplicate packages. Conversely, if everyone uses a GOPATH directory, it will also cause version problems. Each project depends on inconsistent package versions. How to overall plan is also a problem. This is why GOPATH settings were criticized early on.
Go modules
Go Lang version 1.11 introduced a new feature, Go modules, to address the package management mess caused by the anti-human design of GOPATH.
Go modules, an official dependency management tool, provides three important functions:
1.go. The mod file, similar to Node's package.json file, records the dependencies of the current project.
2. Machine-generated transfer dependency description file: go.sum.
3. There are no longer anti-human restrictions on GOPATH, all code can be located in any path of the computer.
go lang1.18 already integrates Go modules, but like Gogolang 1.18 First Refining Tutorial As it is written here, GOPATH mode is still anti-human by default. You have to turn it on manually by command if you want to use it:
go env -w GO111MODULE=on
In order to be able to downward compatible with projects below version go1.11, you can set the compatibility mode:
go env -w GO111MODULE=auto
Tripartite Package Management
Tripartite packages refer to some external open source packages, while it is relatively easy to manage them using the go modules mechanism by first creating a new project directory, such as c:/www/test
cd c:/www/test
After entering the project directory, initialize the project:
go mod init test
System Return:
C:\Users\liuyue\www\test>go mod init test go: creating new go.mod: module test C:\Users\liuyue\www\test>dir 2022/08/12 12:13 <DIR> . 2022/08/12 12:13 <DIR> .. 2022/08/12 12:13 21 go.mod 1 Files 21 Bytes 2 228 directories,767,113,216 Available Bytes
Note here that the project name matches the directory name, go. The mod file is a required configuration file to open modules. It records package data information referenced by the current project. Go. The following keywords are defined in the mod file:
Module: The module path used to define the current project
Go: Used to set the Go version information
require: used to set a specific module version
Exclude: used to exclude a specific module version from use
Replace: used to replace one module version with another
Next, run the go get command to install a three-party package, such as the gin framework:
go get github.com/gin-gonic/gin
Then write the main.go file, which is the main package:
package main import ( "github.com/gin-gonic/gin" ) func main() { d := gin.Default() d.GET("/", func(c *gin.Context) { c.JSON(200, gin.H{"message": "hello go 1.18", "data": ""}) }) d.Run("127.0.0.1:5000") }
This imports the triplet package you just installed and calls it in the main function.
Start the service immediately:
go run main.go
System Return:
C:\Users\liuyue\www\test>go run main.go [GIN-debug] [WARNING] Creating an Engine instance with the Logger and Recovery middleware already attached. [GIN-debug] [WARNING] Running in "debug" mode. Switch to "release" mode in production. - using env: export GIN_MODE=release - using code: gin.SetMode(gin.ReleaseMode) [GIN-debug] GET / --> main.main.func1 (3 handlers) [GIN-debug] [WARNING] You trusted all proxies, this is NOT safe. We recommend you to set a value. Please check https://pkg.go.dev/github.com/gin-gonic/gin#readme-don-t-trust-all-proxies for details. [GIN-debug] Listening and serving HTTP on 127.0.0.1:5000 [GIN] 2022/08/12 - 12:19:20 |[97;42m 200 [0m| 3.8876ms | 127.0.0.1 |[97;44m GET [0m "/" [GIN] 2022/08/12 - 12:19:21 |[90;43m 404 [0m| 0s | 127.0.0.1 |[97;44m GET [0m "/favicon.ico"
Explain that the triple-pack service has been started, access http://localhost:5000:
This is the process for a go lang project to import a tripartite package.
Next, we open the go.mod file in the project:
module test go 1.18 require ( github.com/gin-contrib/sse v0.1.0 // indirect github.com/gin-gonic/gin v1.8.1 // indirect github.com/go-playground/locales v0.14.0 // indirect github.com/go-playground/universal-translator v0.18.0 // indirect github.com/go-playground/validator/v10 v10.10.0 // indirect github.com/goccy/go-json v0.9.7 // indirect github.com/json-iterator/go v1.1.12 // indirect github.com/leodido/go-urn v1.2.1 // indirect github.com/mattn/go-isatty v0.0.14 // indirect github.com/modern-go/concurrent v0.0.0-20180228061459-e0a39a4cb421 // indirect github.com/modern-go/reflect2 v1.0.2 // indirect github.com/pelletier/go-toml/v2 v2.0.1 // indirect github.com/ugorji/go/codec v1.2.7 // indirect golang.org/x/crypto v0.0.0-20210711020723-a769d52b0f97 // indirect golang.org/x/net v0.0.0-20210226172049-e18ecbb05110 // indirect golang.org/x/sys v0.0.0-20210806184541-e5e7981a1069 // indirect golang.org/x/text v0.3.6 // indirect google.golang.org/protobuf v1.28.0 // indirect gopkg.in/yaml.v2 v2.4.0 // indirect )
The three-party packages gin and the three-party packages on which gin depends are clear at a glance.
Internal Package Management
Internal packages refer to the packages within a project. Generally, they are reusable packages that you develop yourself. go modules can also manage internal packages. In the test project you just created, create a new directory, my:
C:\Users\liuyue\www\test>mkdir my C:\Users\liuyue\www\test>dir Driver C Volumes in have no labels. Volume serial number is 0 A64-32BF C:\Users\liuyue\www\test Directory 2022/08/12 12:39 <DIR> . 2022/08/12 12:13 <DIR> .. 2022/08/12 12:18 1,046 go.mod 2022/08/12 12:18 6,962 go.sum 2022/08/12 12:16 228 main.go 2022/08/12 12:39 <DIR> my 3 Files 8,236 byte 3 228 directories,568,178,688 Available Bytes C:\Users\liuyue\www\test>
Then create a new my.go file in my directory:
package my import "fmt" func New() { fmt.Println("I am my package") }
Here we declare that the package matches the directory name, and then we declare a New function.
Then rewrite the main.go content:
package main import ( "fmt" "test/my" ) func main() { fmt.Println("main run") // Use my my.New() }
Program returns:
main run I am my package
By-pass if the package is not under the same project:
├── moduledemo │ ├── go.mod │ └── main.go └── mypackage ├── go.mod └── mypackage.go
At this point, mypackage also needs to initialize the module, which has its own go.mod file, which reads as follows:
module mypackage go 1.18
Then we import it in moduledemo/main.go as follows:
import ( "fmt" "mypackage" ) func main() { mypackage.New() fmt.Println("main") }
epilogue
For Go lang projects, if go mod mode is not enabled, then the project must be placed in the GOPATH/src directory. The project itself can also be viewed as a local package that can be referenced by other projects in the GOPATH/src directory, and can also be introduced by projects in the go modules mode, because the principle of go modules is to address in the GOPATH/src directory first, and if not, to specify directory addressing, but in turn, Items in the GOPATH/src directory cannot be referenced if they are local packages placed in the go modules project, because GOPATH specifies that items must all be placed in the GOPATH/src directory, which will only be addressed in the GOPATH/src directory, which is something we need to be aware of.