go module 介绍

go Module 是 Go 语言的一种依赖管理方式。
在 Go 1.11 版本中出现的,在1.13版本前,需要显式设置环境变量GO111MODULE的值为on。

1.13版本以后,该环境变量被设置为auto,在GOPATH内,GO111MODULE的值为off,也就是使用GOPATH;
如果在GOPATH之外,或者在有go.mod文件的目录下,则GO111MODULE的值为on,开启Go Module特性。

设置代理:go env -w GOPROXY=https://goproxy.cn,direct

查看配置

$ go env
GO111MODULE="on"
GOARCH="amd64"
GOBIN=""
GOCACHE="/Users/fsj/Library/Caches/go-build"
GOENV="/Users/fsj/Library/Application Support/go/env"
GOEXE=""
GOFLAGS=""
GOHOSTARCH="amd64"
GOHOSTOS="darwin"
GOINSECURE=""
GOMODCACHE="/Users/fsj/go/pkg/mod"
GONOPROXY=""
GONOSUMDB=""
GOOS="darwin"
GOPATH="/Users/fsj/go"
GOPRIVATE=""
GOPROXY="https://goproxy.cn,direct"
GOROOT="/usr/local/go"
GOSUMDB="sum.golang.org"
GOTMPDIR=""
GOTOOLDIR="/usr/local/go/pkg/tool/darwin_amd64"
GCCGO="gccgo"
AR="ar"
CC="clang"
CXX="clang++"
CGO_ENABLED="1"
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 -fno-caret-diagnostics -Qunused-arguments -fmessage-length=0 -fdebug-prefix-map=/var/folders/2w/tt1p_4td3yq9xlbl7c2t4jn00000gn/T/go-build597889543=/tmp/go-build -gno-record-gcc-switches -fno-common"

查看帮助信息

$ go help mod
Go mod provides access to operations on modules.

Note that support for modules is built into all the go commands,
not just 'go mod'. For example, day-to-day adding, removing, upgrading,
and downgrading of dependencies should be done using 'go get'.
See 'go help modules' for an overview of module functionality.

Usage:

	go mod <command> [arguments]

The commands are:

	download    download modules to local cache (下载依赖的module到本地cache))
	edit        edit go.mod from tools or scripts (编辑go.mod文件)
	graph       print module requirement graph (打印模块依赖图))
	init        initialize new module in current directory (再当前文件夹下初始化一个新的module, 创建go.mod文件))
	tidy        add missing and remove unused modules (增加丢失的module,去掉未用的module)
	vendor      make vendored copy of dependencies (将依赖复制到vendor下)
	verify      verify dependencies have expected content (校验依赖)
	why         explain why packages or modules are needed (解释为什么需要依赖)

Use "go help mod <command>" for more information about a command.

go get 直接下载需要的包。或者go mod download可以下载所需要的依赖。
注意依赖并不是下载到$GOPATH中,而是$GOPATH/pkg/mod中,多个项目可以共享缓存的module。
里面的mod目录会使用@x.x.x的格式区分不同版本的代码

$ cat go.mod 
module my-go-proj

go 1.13

require (
	github.com/go-sql-driver/mysql v1.5.0
	upper.io/db.v3 v3.7.1+incompatible
)

$ ll /Users/fsj/go/pkg/mod/github.com/go-sql-driver/  
total 0
dr-x------  45 fsj  staff   1.5K 12 30 14:45 mysql@v1.5.0

参考

posted @ 2021-01-18 16:05  畑鹿驚  阅读(317)  评论(0编辑  收藏  举报