本文介绍golang包管理工具。在golang v1.11版本之前使用gopath进行管理,但在不同项目对同一包不同版本依赖时会造成问题。golang v1.11之后的版本引入了go module进行包管理。
GOPATH
在1.11版本之前,golang是通过GOPATH这个环境变量来管理包依赖(包括第三方包和自己工程中的子包)。同时使用go get命令下载的包都会被放在GOPATH指定的目录下面。它的固定格式如下:
$GOPATH
bin/ # Directory where executable binaries are stored
src/ # Directory where Go source files of the dependent packages are stored
github.com/google/go-cmp/
...
pkg/ # Directory where compiled Go object files are stored
...
所有的项目代码,都会放在src目前下面。如果项目代码被放在了其它位置,项目在编译环节会报错。
GO MODULE
在1.11版本之后,引入了GO MODULE。它的主要作用有两个,1是包版本控制(versioning),项目可以指定依赖第三方包的版本号;2是工程代码的位置不再局限在GOPATH目录下(package distribution)。
对项目进行构建时go module 会自动安装 package,它的原则是先拉取最新的 release tag,若无 tag 则拉取最新的 commit
可以使用命令go list -m -u all来检查可以升级的 package,使用go get -u need-upgrade-package升级后会将新的依赖版本更新到 go.mod * 也可以使用go get -u升级所有依赖。
GO111MODULE环境变量
Go.mod文件
示例
module learn
go 1.14
require github.com/pborman/uuid v1.2.1
以上示例比较简单
一般来讲,go.mod 提供了 module、require、replace 和 exclude 四个命令:
- module 语句指定包的名字(路径);
- require 语句指定的依赖项模块;
- replace 语句可以替换依赖项模块;
- exclude 语句可以忽略依赖项模块。
组成部分
- Module import path.
- The version of go with which the module is created
- Dependency requirements of the module for a successful build. It defines both project’s dependencies requirement and also locks them to their correct version.
分别对应示例中的每一行
依赖分类
- Direct -A direct dependency is a dependency which the module directly imports.
- Indirect – It is the dependency that is imported by the module’s direct dependencies. Also, any dependency that is mentioned in the go.mod file but not imported in any of the source files of the module is also treated as an indirect dependency.
Go mod命令
命令 | 作用 |
go mod download | 下载依赖包到本地(默认为 GOPATH/pkg/mod 目录) |
go mod edit | 编辑 go.mod 文件 |
go mod graph | 打印模块依赖图 |
go mod init | 初始化当前文件夹,创建 go.mod 文件 |
go mod tidy | 增加缺少的包,删除无用的包 |
go mod vendor | 将依赖复制到 vendor 目录下 |
go mod verify | 校验依赖 |
go mod why | 解释为什么需要依赖 |
go.sum文件
直接或间接依赖库的校验和,它的主要作用是在编译过程中检查是否有依赖的包发生了版本的变化。因此go.mod和go.sum文件都应该被git仓库管理起来。