go mod 官方推荐包管理工具,是在 golang 1.11 中新加的特性。

如何使用 go mod

go1.11 版本需要手动开启使用 go mod, 设置 go 环境变量 GO111MODULE=on go1.14 版本之后,作为 golang 默认的 包管理工具

go mod 命令

命令 示例 说明
init initialize new module in current directory 当前目录初始化 mod
tidy add missing and remove unused modules 拉取缺少的模块,移除不用的模块
vendor make vendored copy of dependencies 将依赖复制到 vendor 下
download download modules to local cache 下载依赖包
graph print module requirement graph 打印模块依赖图
verify verify dependencies have expected content 验证依赖是否正确
why explain why packages or modules are needed 解释为什么需要依赖

1. 如何在项目中使用

1.1 创建一个新项目 (或非 go mod 包管理项目)

> go mod init projectName
  • go.mod 文件一旦创建后,它的内容将会被go toolchain全面掌控。go toolchain会在各类命令执行时,比如 go get、go build、go mod 等修改和维护 go.mod 文件。

  • 如使用编辑器 goland, 也需要开启设置 Enable Go models intergration

1.2 go mod 关键字

go.mod 提供了 modulerequirereplaceexclude 四个命令

  • module 语句指定包的名字 (路径)
  • require 语句指定的依赖项模块
  • replace 语句可以替换依赖项模块
  • exclude 语句可以忽略依赖项模块

1.3 使用 go get 升级 go mod 中依赖

  • go get package@version 将会升级到指定的版本号 version
  • go get -u package 将会升级到最新的修订版本,如 go get -u github.com/gin-gonic/gin

2. go mod 批量操作

2.1 查看 go.mod 中有更新的直接依赖项

go list -u -f '{{if (and (not (or .Main .Indirect)) .Update)}}{{.Path}}{{end}}' -m all

go list -u -f '{{if (and (not (or .Main .Indirect)) .Update)}}{{.Path}}: {{.Version}} -> {{.Update.Version}}{{end}}' -m all

2.2 批量更新他们

  • 使用 go get -u $()

go get -u $(go list -u -f '{{if (and (not (or .Main .Indirect)) .Update)}}{{.Path}}{{end}}' -m all)

  • 使用 xargs

go list -u -f '{{if (and (not (or .Main .Indirect)) .Update)}}{{.Path}}{{end}}' -m all | xargs go get -u