Understand Go Mod in one article

Go Mod

Go Mod package management tutorial

With the release of go 1.11 , go officially introduced the go module to solve the dependency management problem, and the go module was integrated into the native go cmd.

But if your code base is in $GOPATH , the module function of go1.11 is not enabled by default. It is very simple to enable it. You can enable go module through an environment variable:

export GO111MODULE=on

Go Mod and GoPath

Now the modules mechanism is still in its early stages, so golang provides an environment variable "GO111MODULE" with a default value of auto.

If there is a go.mod file in the current directory, use go modules. Otherwise, use the old GOPATH and vendor mechanism, because go get will only download go modules under the modules mechanism. This behavior will become the default in future versions. Here We can keep auto, if you want to use modules directly without going over from GOPATH, then set "GO111MODULE" to on.

Unlike traditional GOPATH, modules do not need to include subdirectories such as src and bin. A source code directory or even an empty directory can be used as a module, as long as it contains the go.mod file.

About $GOPROXY

use

When we use go, go will download the required dependencies directly from the code base by default. The environment variable GOPROXY allows us to control where we download the source code.

If GOPROXY is not set, go will download the dependent code directly from the code base. If you set this environment variable like the following, then you will download all the source code through goproxy.io . The command to set the proxy is as follows:

export GOPROXY=https://goproxy.io

You can turn off proxy by blanking this environment variable, the command is as follows:

export GOPROXY=

principle

Before the execution go get golang.org/x/net, the code base then the net will be downloaded to the local GOPATH in the future there any reference to the project golang.org/x/netwill not go to download the code base, because the local GOPATH already have, even if the wrong version, golang will be cited.

But with the introduction of the module concept into the go language, each introduced module has a version. With the continuous update and iteration of the code base, even if you refer to the same code base, you may use different tags or commit hashes. Based on this status quo, go1.11 modules will download source code more frequently than before.

But based on the Internet with Chinese characteristics in China, it is sometimes difficult for us to get the dependent source code we need, which leads to project compilation failures and CI failures. Therefore, we need a proxy.

Proxy settings

Proxy address

There are mainly two addresses, as follows:

https://goproxy.io
https://athens.azurefd.net

The above two addresses can be chosen at will according to personal preference.

Setting method

Windows

$env:GOPROXY = "https://goproxy.io"

Linux

export GOPROXY=https://goproxy.io

Go Mod use

Initialization of go module

We first, create an empty project folder

E:\Code\gomod

Next, we initialize the project:

#Linux
export GO111MODULE=on
export GOPROXY=https://goproxy.io

#Windows
$env:GO111MODULE=on
$env:GOPROXY="https://goproxy.io"

go mod init [module name]

After the initial completion, a go.mod file will be generated in the directory with only one line "module test".

Package management

When we use go build, go test and go list, go will automatically update the go.mod file and write dependencies into it. If you want to handle dependencies manually, use the following command:

go mod tidy

This command will automatically update the dependencies and download the package into the cache.

Common commands for Go Mod

go.mod file command

go.mod provides four commands of module, require, replace and exclude, as follows:

command description
module The statement specifies the name (path) of the package
require The dependency module specified by the statement
replace Statement can replace dependency module
exclude Statement can ignore dependent modules

Common commands for go mod

command description
download To download the module to the local cache, you can check the details through the command go env. The environment variable GOCACHE is the address of the cache. If the content of the folder is too large, you can use the command go clean -cache
edit Edit the go.mod file from a tool or script
graph Print module demand diagram
init Initialize a new module in the current directory
tidy Add missing modules and remove useless modules
verify Verify that the dependencies achieve the intended purpose
why Explain why a package or module is needed

Go Mod case

Reference third-party libraries

We first create a main.go file in E:\Code\gomod and output the following content:

package main
    
    import (
    	"context"
    	"log"
    	"time"
    
    	"github.com/chromedp/chromedp"
    )
    
    func main() {
    
    
    	// create chrome instance
    	ctx, cancel := chromedp.NewContext(
    		context.Background(),
    		chromedp.WithLogf(log.Printf),
    	)
    	defer cancel()
    
    	// create a timeout
    	ctx, cancel = context.WithTimeout(ctx, 15*time.Second)
    	defer cancel()
    
    	// navigate to a page, wait for an element, click
    	var example string
    	err := chromedp.Run(ctx,
    		chromedp.Navigate(`https://golang.org/pkg/time/`),
    		// wait for footer element is visible (ie, page is loaded)
    		chromedp.WaitVisible(`#footer`),
    		// find and click "Expand All" link
    		chromedp.Click(`#pkg-examples > div`, chromedp.NodeVisible),
    		// retrieve the value of the textarea
    		chromedp.Value(`#example_After .play .input textarea`, &example),
    	)
    	if err != nil {
    
    
    		log.Fatal(err)
    	}
    	log.Printf("Go's time.After example:\n%s", example)
    }

Next, we start downloading the package and enter the following command:

go mod tidy

Then, we can find that go.mod and go.sum both increase the dependency files of the package. Now, we can directly compile, enter the following command:

go build

Reference custom library

We first create the following directory:

E:\Code\wolferserver
E:\Code\wolferserver\base
E:\Code\wolferserver\base\configs

E:\Code\wolferserver\src
E:\Code\wolferserver\src\logicserver

Next, we create the following files:

E:\Code\wolferserver\base\configs\configs.go
E:\Code\wolferserver\src\logicserver\main.go

The file content of each file is as follows:

//configs.go
package configs

import "fmt"

func Demo(){
	fmt.Println("Hello Demo")
}
    
    
//main.go
package main

import (
	"github.com/gin-gonic/gin"
	"wolferserver/base/configs"
)

func main(){
	logInit()
}

func logInit() {
	configs.Demo()

	gin.New()
}

Finally, we can directly enter the following command to run our program:

go run src/lpgicserver/main.go

version control

Another important function of package management is package version control. Modules can do the same.

go.sum

github.com/chromedp/cdproto v0.0.0-20190429085128-1aa4f57ff2a9 h1:ARnDd2vEk91rLNra8yk1hF40H8z+1HrD6juNpe7FsI0=

The first part is the name of the package, which is the part that needs to be written when importing, and the version number after the space is the version number, which follows "version number + timestamp + hash".

When we specify the version ourselves, we only need to specify the version number. If there is no version tag, we need to find the time and hash value of the corresponding commit. The latest version of the package is used by default.

Change version

Now we need to modify the dependencies, we want to use the v0.1.0 version of chromedp, just the following command

go mod edit -require="github.com/chromedp/[email protected]"

Add the version number you need after @. go.mod has been modified. We also need to let go modules update the dependencies, here we can manually go mod tidy.

Haicoder (www.haicoder.net)

Guess you like

Origin blog.csdn.net/weixin_41384860/article/details/109407708