尊重生命,即便是蚂蚁,也不会踩死。 -- JayL
如何实现企业内项目的Go Module
工程化迁移?
以本人以往所在公司的实际现状做为样例,说明具体的Go Module
工程化迁移过程。html
原有Go项目均采用单一vendor
的模式进行依赖控制,即企业内全部Go项目的第三方依赖均引用该统一的vendor
仓库,由专人专组独立维护。这样作的好处就是依赖包不会随实际开发者的版本变动而变动,企业内部维护一套相对稳定的版本,缺点就是缺乏了依赖包的版本控制。git
向Go Module
工程化迁移的目标就是保持本地版本的稳定的同时兼顾版本控制功能。github
modules
仓库在非Go Module
项目中,全部项目的依赖包,使用了vendor
仓库,在迁移到Go Module
模式下,一样须要相应的modules
仓库, 来保证本地开发包依赖版本的稳定。golang
该modules
仓库的依赖包从何而来。不妨看看:apache
$: tree -L 1 $GOPATH/pkg/mod/cache/download ├── cloud.google.com ├── git.apache.org ├── git.yixindev.net ├── github.com ├── go.opencensus.io ├── go.uber.org ├── golang.org ├── gonum.org ├── google.golang.org ├── gopkg.in ├── gotest.tools ├── honnef.co ├── k8s.io └── layeh.com
这就是咱们要维护的modules
仓库依赖包。在开发过程当中,新的依赖包都会下载到这个路径。将新的依赖包版本复制到modules
仓库相应的路径。就完成了modules
仓库依赖包的版本维护。bash
须要注意的点是:gitlab
咱们是从$GOPATH/pkg/mod/cache/download
目录中复制新的依赖包到modules
仓库中。但并非全部的文件都须要进行维护,特别是本地下载过程当中的一些临时文件。优化
$: tree -L 1 $GOPATH/pkg/mod/cache/download/github.com/x-mod/httpclient/@v/ ├── list ├── list.lock ├── v0.1.2.info ├── v0.1.2.lock ├── v0.1.2.mod ├── v0.1.2.zip ├── v0.1.2.ziphash ├── v0.2.0.info ├── v0.2.0.lock ├── v0.2.0.mod ├── v0.2.0.zip ├── v0.2.0.ziphash ├── v0.2.1.info ├── v0.2.1.lock ├── v0.2.1.mod ├── v0.2.1.zip └── v0.2.1.ziphash
在这个github.com/x-mod/httpclient
依赖包中,咱们仅仅须要具体版本的四个类型文件:google
其它类型的文件,是不须要进行modules
仓库维护的。因此能够在modules
仓库中经过.gitignore
进行忽略。.net
CI
过程更新完成了modules
仓库的维护后,咱们就能够对原有项目的CI
过程进行更新了。在CI
编译机或者容器上
modules
repo 到指定位置 path/to/modules
GoModule
编译选项, 设置export GO111MODULE=on
GoProxy
环境变量, 设置经过本地文件代理: export GOPROXY=file:///path/to/modules
如今全部GO项目就会开启GoModule
选项同时,能够完成依赖包的版本控制。如何缺乏依赖包,只须要从本地将新增依赖包的版本添加到modules
仓库便可。
GoGet
代理优化若是阅读了Go Get
原理以后,针对企业依赖包的GoGet
,咱们能够写一个简单的http
代理程序, 这样就设定本身的:
// Example // code server http://aaa.com:888/user/repo.git // code import path: bbb.com/user/repo // // host => aaa.com:888 // vcs => git // root => bbb.com type Getter struct { host string //gitlab address vcs string //git root string //git } func NewGetter(host string, vcs string, root string) *Getter { return &Getter{ host: host, vcs: vcs, root: root, } } func (x *Getter) ServeHTTP(w http.ResponseWriter, r *http.Request) { if r.URL.Query().Get("go-get") == "1" { sp := strings.Split(r.URL.Path[1:], "/") if len(sp) < 2 { http.Error(w, fmt.Errorf("unsupport path: %s", r.URL.Path).Error(), http.StatusBadRequest) return } prefix := fmt.Sprintf("%s/%s/%s", x.host, sp[0], sp[1]) repository := fmt.Sprintf("%s/%s/%s.%s", x.root, sp[0], sp[1], x.vcs) fmt.Fprintf(w, `<html><head><meta name="go-import" content="%s %s %s" /></head></html>`, prefix, x.vcs, repository) log.Println("go get [", prefix, "] from repository [", repository, "].") return } http.Error(w, fmt.Errorf("unsupport request: %s", r.URL.Path).Error(), http.StatusBadRequest) }
经过这个简单的代理,你就能够实现:
code server http://aaa.com:888/user/repo.git
code import path: bbb.com/user/repohost => aaa.com:888
vcs => git
root => bbb.com
这样的非标依赖包的拉取了。
这一篇拖了很久,花一个小时完结掉这个系列。
更多文章可直接访问我的BLOG:GitDiG.com