Go mod 的三种开启模式
- GO111MODULE
- on:支持Go mod模式
- off:不支持Go mod模式
- auto (默认模式):如果代码在gopath下,则自动使用gopath模式;如果代码不在gopath下,则自动使用GO mod模式。
- 开启方式:
- Windows中,在环境变量中添加变量即可,变量名为 GO111MODULE ,变量值可设置为 on、off、auto。
- Linux中,只要在 /etc/profile 中添加 export GO111MODULE=on 或 export GO111MODULE=off 或 export GO111MODULE=auto。然后执行 source /etc/profile 刷新即可。
范式
go mod [arguments]
command命令
download
go download [-x] [-json] [modules]
作用:下载指定名字的模块,可为选择主模块依赖的模块匹配模式,或path@version形式的模块查询。如果download不带参数则代表英语与是主模块的所有依赖。
go mod download
go mod download
标志:
-json-x
edit
go mod edit [editing flags] [go.mod]
作用:edit提供一个编辑go.mod的命令行接口,主要提供给工具或脚本使用。它只读取go.mod;不查找涉及模块的信息。默认情况下,edit读写主模块的go.mod文件,但也可以在标志后指定不同的目标文件。
标志:
type Module struct {
Path string
Version string
}
type GoMod struct {
Module Module
Go string
Require []Require
Exclude []Module
Replace []Replace
}
type Require struct {
Path string
Version string
Indirect bool
}
type Replace struct {
Old Module
New Module
}
-require-droprequire-exclude-dropexclude-replace-dropreplace
注意这只描述go.mod文件自身,不描述其他间接引用的模块。对于构建可使用的的模块的完整集合,使用“go list -m -json all”。
-require-exclude
graph
go mod graph
作用:以文本形式打印模块间的依赖关系图。输出的每一行行有两个字段(通过空格分割);模块和其所有依赖中的一个。每个模块都被标记为path@version形式的字符串(除了主模块,因其没有@version后缀)。
init
go mod init [module]
module
tidy
go mod tidy [-v]
作用:确保go.mod与模块中的源代码一致。它添加构建当前模块的包和依赖所必须的任何缺少的模块,删除不提供任何有价值的包的未使用的模块。它也会添加任何缺少的条目至go.mod并删除任何不需要的条目。
标志:
-v
vendor
go mod vendor [-v]
作用:重置主模块的vendor目录,使其包含构建和测试所有主模块的包所需要的所有包。不包括vendor中的包的测试代码。
标志:
-v
verify
go mod verify
作用:检查存储在本地下载源代码缓存中的当前模块的依赖,是否自从下载之后未被修改。如果所有模块都未被修改,打印“all modules verified”。否则,报告哪个模块已经被修改并令“go mod”以非0状态退出。
why
go mod why [-m] [-vendor] packages...
作用:输出每个包或者模块的引用块,每个块以注释行“# package”或“# module”开头,给出目标包或模块。随后的行通过导入图给出路径,一个包一行。每个块之间通过一个空行分割,如果包或模块没有被主模块引用,该小节将显示单独一个带圆括号的提示信息来表明该事实。
标志:
-m-vendor
go.mod文件
模块版本是由源文件树定义的,在其根目录中有一个go.mod文件。当go命令运行时,它查找当前目录然后查找相继的父目录来找出go.mod,go.mod标记主模块的根。
///**/
动词类型:
- module:定义模块路径。
- go:设置期望的语言版本。
- require:依赖要求一个给定版本或者之后的特定模块。
- exclude:从使用中排除特定模块版本。
- replace:以一个不同的,模块版呢嘛提到另一个模块版本。
exclude和replace只应用在主模块的go.mod中,并且在依赖中会被忽略。
常见错误汇总
go: modules disabled inside GOPATH/src by GO111MODULE=auto; see 'go help modules'
go mod init
go: modules disabled inside GOPATH/src by GO111MODULE=auto; see 'go help modules'
开启go module:
set GO111MODULE=on //windowsexport GO111MODULE=on //linux
$GOPATH/go.mod exists but should not
GO 1.11或之后模块遇到这个问题:
$GOPATH/go.mod exists but should not
开启模块支持后(set GO111MODULE=on),并不能与GOPATH从env中移出即可(unset GOPATH),可运行“unset GOPATH && make”