(Photo by Jonathon Young)
上篇 Golang 1.11 新功能介紹 – Modules 已經介紹 Go modules 基本用法,之前的例子大都拉取 Github public 專案,這篇說明如何下載企業內部自建的 Gitlab, Gitea, Gogs server,使用 insecure (HTTP) 的人一定要看。
直接使用 go mod 下載 -> 失敗
Golang 1.11 提供了方便的內建指令 go mod
,並且將其內建到所有的 go command,指令說明如下:
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
裡面有個 download 指令可用,但直接拿它來下載公司自建 git repo 會發生慘案
$ go mod download
go: insecure-git.com/myOrg/[email protected]: unrecognized import path "insecure-git.com/myOrg/myPackage" (https fetch: Get https://insecure-git.com/myOrg/myPackage?go-get=1: dial tcp 10.10.10.99:443: connect: connection refused)
go get
有個 insecure
參數讓用戶拉取 insecure git,也就是非 HTTPS 的 git server,但這方便的東西並沒有被放入原生 mod 指令,有人嘗試請官方加入,但目前被打槍中,詳見 cmd/go: mod download doesn’t allow insecure download · Issue #27332,官方並不希望再開 insecure 巧門,畢竟現在到處都是免費的 SSL Certificate 如 Let’s Encrypt,有興趣可以看我之前的文章: 五分鐘輕鬆搞定免費SSL Certificate by Let’s Encrypt
後來找到個 workaround,利用 此修正,讓 mod 可以吃到 go get -insecure
相關設定,在下面的範例中,我想將 http://insecure-git.com/myOrg/myPackage v0.0.1
導入當下專案。
- 將 rewrite rule 加到
~/.gitconfig
,避免打帳號密碼
[url "g[email protected]:"]
insteadOf = http://insecure-git.com/
- 進入專案目錄,並將此行加到
go.mod
require
module myProject
require (
insecure-git.com/myOrg/myPackage v0.0.1
)
- 手動下載 package,此時可看到版本資訊被加到
go.sum
檔案
$ go get -v -d -insecure insecure-git.com/myOrg/myPackage/...
go: downloading insecure-git.com/myOrg/myPackage v0.0.1
$ head go.sum
insecure-git.com/myOrg/myPackage v0.0.1 h1:enopSaOi4LJPgW0f5iOZPzkf1vXsW3Y9Ov1M7zYBOZM=
insecure-git.com/myOrg/myPackage v0.0.1/go.mod h1:OkL6Do97MMRxNQif6+7k6tJ34nD2xHptBBj6zdj273Q=
- 將 mod cache 的內容下載到專案內的
vendor/
目錄,方便 gocode 產生 autocomplete
$ go mod vendor
請留言討論 go modules 的問題,一路從 gb, glide, govendor, dep 用起來, modules 已經達到一定成熟度(定版、相依性處理等),可以放心搬家了。