Go modules
是官方推出的依赖管理工具,比go dep
更加好用。
介绍
Go modules
有3个重要的功能:
- go.mod 记录依赖
- go.sum 依赖项描述文件,自动生成
- 没有 GOPATH 限制
Go modules
出现在 1.11 及其以上版本,1.13 已经默认开启 Go modules
,手动开启
go env -w GO111MODULE=on
go.mod 关键字
- module:定义当前项目的模块路径
- go:设置
Go
版本信息 - require:设置一个特定的模块版本
- exclude:从使用中排除一个特定的模块版本
- replace:将一个模块版本替换为另一个模块版本
help
# go help mod
Usage:
go mod <command> [arguments]
The commands are:
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 needed
使用
- 初始化
# mkdir go-mod-demo && cd go-mod-demo
# go mod init go-mod-demo
go: creating new go.mod: module go-mod-demo
# ls
go.mod
# cat go.mod
module go-mod-demo
go 1.15
- 下载依赖
go mod vendor