In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-02-26 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)05/31 Report--
This article mainly explains "how to use go's modules". Interested friends may wish to have a look at it. The method introduced in this paper is simple, fast and practical. Let's let the editor take you to learn how to use go's modules.
Basic introduction to 1.go modules 1.1 commands provided
Execute go mod help view commands and instructions in shell in the go environment.
Usage: go mod [arguments] The commands are: environment variables provided by download download modules to local cache edit edit go.mod from tools or scripts graph print module requirement graph init initialize new module in current directory tidy add missing and remove unused modules vendor make vendored copy of dependencies verify verify dependencies have expected content why explain why packages or modules are needed1.2
Look at the environment variables of go with go env. Of all the environment variables provided by go, one is related to go mod.
GO111MODULE= "on" GOPROXY= "https://goproxy.cn,direct"GONOPROXY="git.example.com,x1"GONOSUMDB="git.example.com,x1"GOPATH="/home/go-project/"GOPRIVATE="git.example.com,x1"GOSUMDB="sum.golang.org"# omits the rest of the environment variables... 1.2.1 description
1) GO111MODULE
The go language provides three values of the GO111MODULE environment variable for the switch of GO111MODULE:
Auto: as long as the go.mod file is included in the project, start the project's go modules, which is still the default in Go1.11 to Go1.14.
On: start go modules
Off: turn off go modules
2) GOPROXY
The default proxy in go env is GOPROXY= "https://proxy.golang.org,direct", but it is inaccessible in China. It needs to be set to the domestic proxy address GOPROXY=" https://goproxy.cn,direct".
The value of GOPROXY is a list of Go module proxies split in English "," allows you to set multiple module proxies, assuming you don't want to use it, you can also set it to "off", which will prohibit Go from using any Go module proxies in subsequent operations.
Direct
In fact, "direct" is a special indicator that instructs Go to pull back to the source address of the module version (such as GitHub, etc.). The scenario is as follows: when the last Go module agent in the value list returns a 404 or 410 error, Go automatically tries the next one in the list. When it encounters "direct", it goes back to the source address to fetch, and when it encounters EOF, it terminates and throws something like "invalid version: unknown revision..." Donovan's mistake.
Execute set GO111MODULE=on in cmd
3) GONOPROXY/GONOSUMDB/GOPRIVATE
These three environment variables are used when the current project relies on private modules, such as your company's private git repository or the private library in github, which belong to private modules and need to be set, otherwise the pull will fail. For some of your own private module code, you need to set it on GOPRIVATE, and you will be prompted for a user name and password when pulling.
You can set multiple, separated by English commas, or use wildcards, etc.
Go env-w GOPRIVATE= "git.example.com,github.com/eddycjy/mquote" go env-w GOPRIVATE= "* .example.com" # basic use of the domain name 2.go modules with example.com
Once go modules is turned on, you can create the project and generate the mod file to manage all the dependencies of the project. The following is the configuration of the go env environment:
GO111MODULE= "auto" GOARCH= "amd64" GOBIN= "/ go/bin/" GOCACHE= "/ root/.cache/go-build" GOENV= "/ root/.config/go/env" GOEXE= "GOFLAGS="GOHOSTARCH=" amd64 "GOHOSTOS=" linux "GOINSECURE="GONOPROXY="GONOSUMDB="GOOS=" linux "GOPATH=" / home/go-project/ "GOPRIVATE="GOPROXY=" https://goproxy.cn, Direct "GOROOT=" / go "GOSUMDB=" sum.golang.org "GOTMPDIR="GOTOOLDIR=" / go/pkg/tool/linux_amd64 "GCCGO=" gccgo "AR=" ar "CC=" gcc "CXX=" grub + "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-build940953411=/tmp/go-build-gno-record-gcc-switches "
GOPATH is set to / home/go-project/, and the proxy points to the domestic proxy address to prevent foreign images from being inaccessible.
2.1 initialize the project
Create a new project example.com/mycount/hello,example.com simulation github.com,mycount simulation account under the $GOPATH directory, where hello is the final project name. Directory and file structure:
2.1.1 initialize the .mod file
Execute go mod init example.com/mycount/hello to initialize the mod file for the hello project under the hello directory, as follows:
After the initialization operation, a go.mod file is generated, which contains only two lines:
Module: the module path used to define the current project
Go: it is used to identify the Go language version of the current module. The value is the version when the module was initialized. So far, it is only an identification function.
2.1.2 A simple example
Write a main.go file in the hello directory, using a third-party library.
Package mainimport ("net/http"github.com/gin-gonic/gin"github.com/json-iterator/go") type resp struct {Status int `json: "status" `Message string `json: "message" `} func main () {router: = gin.Default () router.GET ("/", hello ()) if err: = router.Run (": 6060") Err! = nil {panic (err)} func hello () gin.HandlerFunc {return func (context * gin.Context) {strResp, _: = jsoniter.MarshalToString (resp {Status: http.StatusOK, Message: "success",}) context.String (http.StatusOK StrResp)}}
Execute the go get command under the hello directory to pull the dependent library:
After pulling the dependency, a go.mod and go.sum file, the go.mod file, is generated:
The content of go.sum:
At the same time, there is an additional pkg file in the $GOPATH directory, which has a dependency on the pulled file. This file is a global cache
2.1.3 go get for go modules
When pulling project dependencies, you will find that the pull process is divided into three steps, namely finding (discovery), downloading (download) and extracting (extraction), and the pull information is divided into three sections:
It should be noted that the commit time of the pulled version is based on the UTC time zone, not the local time zone. At the same time, we will find that the version pulled by our go get command is v0.0.0. This is because we directly execute go get-u to obtain the version, and do not specify any version information. It is up to Go modules to choose according to the internal rules.
So I want to choose how the specific version should be implemented, as follows:
3. Publish your own packages using go mod 3.1 publish public packages
The public release package does not need to modify some of the environment variables in go env, just the default environment variables.
3.1.1 implementation of package
Suppose we have a module that needs to be provided to a third party, and the package is published on gittee. Suppose my account on gitee is gitee.com\ luciferofwg. Later, we will maintain the version according to iteration or function, and release the latest version whenever there is an update or upgrade, and the version follows the semantic version definition. What is a semantic version?
This package contains a function to print a sentence, as follows:
/ / hello.gopackage helloimport "fmt" func SayHello () {fmt.Println ("hello world")}
Create a new directory hello under GOPATH, enter the hello directory under the command line, and execute go mod init to generate the go mod file, as follows:
The generated package is named gitee.com/luciferofwg/hello, which is import when the package is referenced later.
Submit the hello repository to gitee and complete the first phase of the package release.
3.1.2 release of packages
After the previous step, there is an open warehouse called hello in the warehouse, as follows:
If we think this version is stable and reliable, we need to release a usable version. The process of gitee release is as follows:
Click the create button on the right side of the warehouse, create the release number in the pop-up page, and click create release to complete the release.
Figure 1 create a distribution
Figure 2 release information
Figure 3 created distribution
So far, we have released a version of v1.0.4.
3.1.3 use of packages
For packages that have been released, here is how to use it. First define a package called test, because test is the calling program, so when we initialize mod, we initialize it directly according to the name of the program, that is, go mod test, complete the initialization. As follows:
Write the following code in the test directory:
Package mainimport "gitee.com/luciferofwg/hello" func main () {hello.SayHello ()}
Then execute go mod tidy collation go mod on the command line, and go mod will pull the corresponding package from the Internet according to the package name according to the reference relationship of the package. After the execution is completed, the go.mod is as follows:
The result of the operation:
It is important to note that:
The latest release version is pulled by default. If you want to make a version, you only need to change the last version number of require in go.mod. How to modify the edit entry of the go.mod reference go help mod command.
3.2 publish a private package
3.2.1 Modification of go env environment variables and git configuration
Modification of 1.go env environment variable
The biggest difference between a private package and a public package is the permission and git process of pulling the package, which requires modification of some parameters in go env. Some parameters involved
GOINSECURE,GONOPROXY,GONOSUMDB, meaning:
GOINSECURE: if the code repository is self-built and does not have a "legal" certificate, you need to configure this information
GONOPROXY: the domain name or warehouse address configured in this variable will not leave the proxy (we set the proxy for cn earlier)
The package will be verified after GONOSUMDB:1.15. The configuration here has the same meaning as GONOPROXY.
Take a look at our go env variable, which has been modified before, as follows:
Note:
When you modify the configuration under windows, you can directly add the above configuration to the environment variable of the system, and modify it in the configuration file of bash under linux (you can search for specific changes).
Modification of 2.git configuration
Since it is a private package, you need to obtain the permission to pull it when pulling it. The default https or http method requires a password. If we have configured the private key on the corresponding gitee locally, and have configured permissions on the account corresponding to the gitee, then we can access the private repository through git@xxx.
Open the configuration of the local git. Under windows is the c:\\ user\\ user name\\ .bashconfig file. Open this file. Add the following code:
[url "git@gitee.com:"] insteadof = https://gitee.com
It means that the process of accessing https://gitee.com is replaced with git@gitee.com:, that is, private libraries can be accessed through bash.
3.2.2 implementation of private packages
1. Private package implementation
We create a private repository called hi, which contains a function SayHello to print hello world.
Similarly, create a go.mod, implement the SayHello function, and push it to gitee.
Figure 1 Private Warehouse hi
two。 Function and source code
/ / SayHello function of hi package package hiimport "fmt" func SayHello () {fmt.Println ("hi, world")}
Go.mod of the hi package
3.2.3 release of private packages
According to the above source code, release the version in the same way.
Figure 1 released version 1.0.0
3.2.4 references to private packages
If you have already configured the parameters of go env and the git configuration, the process is the same as that of the public package. Based on the original version, add a function reference and import of the hi package, execute go mod tidy in the test directory, and the released package will be pulled automatically.
Package mainimport ("gitee.com/luciferofwg/hello"gitee.com/luciferofwg/hi") func main () {hello.SayHello () hi.SayHello ()}
The go.mod of the test program is as follows:
At this point, I believe you have a deeper understanding of "how to use go's modules". You might as well do it in practice. Here is the website, more related content can enter the relevant channels to inquire, follow us, continue to learn!
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 0
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.