设置Module环境变量
// linux
export GO111MODULE=on
// windows
set GO111MODULE=on
初始化
// 初始化Module需要进入所在项目的根目录
go mod init <project name>
设置代理
设置环境变量GOPROXY的值为 https://goproxy.io 或https://athens.azurefd.net
添加一个aliyun的代理
https://mirrors.aliyun.com/goproxy/
// linux
export GOPROXY=https://mirrors.aliyun.com/goproxy/
// windows
set GOPROXY=https://mirrors.aliyun.com/goproxy/
go mod 使用方法
// 初始化模块
go mod init <项目模块名称>
// 依赖关系处理,根据go.mod文件
go mod tidy
// 将依赖包复制到项目下的 vendor目录
go mod vendor // 如果包被屏蔽(墙),可以使用这个命令,随后使用go build -mod=vendor编译
// 显示依赖关系
go list -m all
// 显示详细依赖关系
go list -m -json all
// 下载依赖
go mod download [path@version] // [path@version]是非必写的
// 本地包引入
require (
test v0.0.0
)
replace (
test => ../test
)
注意:
1.引入的包必须也是gomod的(有.mod文件)
2.replace时必须使用相对路径比如../ ./
3.require 的包后必须带版本号,replace中可带可不带
go mod 命令
命令 | 说明 |
---|---|
download | download modules to local cache(下载依赖包) |
edit | edit go.mod from tools or scripts(编辑go.mod) |
graph | print module requirement graph (打印模块依赖图) |
init | initialize new module in current directory(在当前目录初始化mod) |
tidy | add missing and remove unused modules(拉取缺少的模块,移除不用的模块) |
vendor | make vendored copy of dependencies(将依赖复制到vendor下) |
verify | verify dependencies have expected content (验证依赖是否正确) |
why | explain why packages or modules are needed(解释为什么需要依赖) |