说明: go module增在快速的成长中,最近每个版本中(1.11 ~ 1.13)都有很大的变动。 建议你阅读官方的wiki了解go module最新的知识: go/wiki/Modules

最新扩展阅读(go 1.13):Go module 再回顾。

moduleweb assemblygo modulehello world
go help modgo help modulesgo help module-getmodulemodule

我也在摸索中前行, 记录了摸索过程中的一些总结,希望能给还在挣扎中的Gopher一些帮助。

Introduction to Go Modules 是一篇很好的go module 入门介绍, 如果你仔细阅读了它,应该就不需要看本文了。

GO111MODULE

go moduleGO111MODULE=on

既有项目

$GOPATH/github.com/smallnest/rpcxgo mod init github.com/smallnest/rpcxgo.modmodule github.com/smallnest/rpcx
go get ./...go.mod-tags
go mod tidygo.modtags
go.modlatestgo.sum

新的项目

GOPATH
go mod init packagenamego.modrequire github.com/smallnest/rpcx latest
go mod download$GOPATH$GOPATH/pkg/mod

go mod命令

1
2
3
4
5
6
7
8
download download modules to local cache (下载依赖的module到本地cache))
edit edit go.mod from tools or scripts (编辑go.mod文件)
graph print module requirement graph (打印模块依赖图))
init initialize new module in current directory (再当前文件夹下初始化一个新的module, 创建go.mod文件))
tidy add missing and remove unused modules (增加丢失的module,去掉未用的module)
vendor make vendored copy of dependencies (将依赖复制到vendor下)
verify verify dependencies have expected content (校验依赖)
why explain why packages or modules are needed (解释为什么需要依赖)
go mod download -dir
1
2
3
4
go mod download -dir /tmp
flag provided but not defined: -dir
usage: go mod download [-dir] [-json] [modules]
Run 'go help mod download' for details.
dirdir

看这些命令的帮助已经比较容易了解命令的功能。

翻墙

golang.org/xgo.modreplace
1
2
3
4
5
replace (
golang.org/x/crypto v0.0.0-20180820150726-614d502a4dac => github.com/golang/crypto v0.0.0-20180820150726-614d502a4dac
golang.org/x/net v0.0.0-20180821023952-922f4815f713 => github.com/golang/net v0.0.0-20180826012351-8a410e7b638d
golang.org/x/text v0.3.0 => github.com/golang/text v0.3.0
)
replacego.modgithub.com/smallnest/rpcxgo.modreplacego.modrequirerpcxreplacego getgolang.org/x
replace

版本格式

下面的版本都是合法的:

1
2
3
4
5
gopkg.in/tomb.v1 v1.0.0-20141024135613-dd632973f1e7
gopkg.in/vmihailenco/msgpack.v2 v2.9.1
gopkg.in/yaml.v2 <=v2.2.1
github.com/tatsushid/go-fastping v0.0.0-20160109021039-d7bb493dee3e
latest

go get 升级

go get -ugo get -u=patchgo get package@versionversion

go mod vendor

go mod vendor

go module, vendor 和 Travis CI