go modules
是官方推出的依赖管理工具,go modules
本质是一种 GOPATH
之外包管理工具。出现的目的是替代 go dep 时代
介绍
优点:
- 代码不用放置在 $GOPATH 目录下
- go mod 不再依靠 $GOPATH,使得它可以脱离 $GOPATH 来创建项目
- 自动下载依赖管理
- 支持版本控制
- 支持replace机制,替代被墙的包
启用 Go modules
只需要执行:
go mod init <mod-name(project-url)>
// eg
go mod init github.com/xiexianbin/gseo
自动生成的文件如下:
- go.mod 记录依赖
- go.sum 依赖项描述文件,记录依赖的版本、校检和等
- vendor 目录,存放依赖文件
go Module的状态
Go modules
出现在 1.11 及其以上版本,1.13 已经默认开启 Go modules
- GO111MODULE=off,go命令行将不会支持module功能
- GO111MODULE=on,go命令行会使用modules,而一点也不会去GOPATH目录下查找
- GO111MODULE=auto,默认值,放在非 $GOPATH 目录下,且有 go.mod 文件时为 on,否则为 off
手动开启命令:
go env -w GO111MODULE=on
go.mod 关键字
- module:定义当前项目的模块名称
- go:设置
Go
版本信息
- require:设置特定的依赖包列表以及版本
- exclude:从使用中排除一个特定的依赖包列表
- replace:替换依赖包列表
- 示例:
go mod edit -replace=golang.org/x/crypto=github.com/golang/crypto@latest
go mod edit -replace=gitee.com/openeuler/go-gitee=gitee.com/xiexianbin/go-gitee@latest
,go.mod 中增加一行
replace gitee.com/openeuler/go-gitee => gitee.com/xiexianbin/go-gitee latest
命令
go help mod
Go mod provides access to operations on modules.
Note that support for modules is built into all the go commands,
not just 'go mod'. For example, day-to-day adding, removing, upgrading,
and downgrading of dependencies should be done using 'go get'.
See 'go help modules' for an overview of module functionality.
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
Use "go help mod <command>" for more information about a command.
常用命令
- go mod tidy //整理依赖,添加缺少的模块,移除不用的模块
- go mod download //下载依赖包
- go mod graph //打印模块依赖图
- go mod vendor //将依赖复制到vendor下
- go mod verify //校验依赖
- go mod why //解释为什么需要依赖
- go mod edit -replice=golang.org/x/crypto=github.com/golang/crypto@latest // 替换包地址
- go list -m -json all //依赖详情
使用示例
初始化
# 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
升级依赖
使用 go-mod-upgrade
交互式地更新过时的 Go
依赖项。
$ go get -u github.com/oligot/go-mod-upgrade
$ go-mod-upgrade
说明:
- green : minor update
- yellow : patch
- red : prerelease
FAQ
golang dep 导入本地依赖库
目录结构如下:
# cd $GOPATH
# ls src/github.com/x-sso
golang-socials golang-socials-example # 需要引入本地 `github.com/x-sso/golang-socials` 的包
在Gopkg.toml
中添加:
ignored = ["github.com/x-sso/golang-socials/*"]
在go.mod
中添加:
replace github.com/x-sso/golang-socials => ../golang-socials
在golang-socials
目录中执行:
dep ensure -v
go mod vendor