如何使用 go get 下载 gitlab 私有项目?

在我们使用golang开发项目时,会遇到私有仓库问题,本文章讲解golang中私有仓库的使用

本文由 简悦 SimpRead 转码, 原文地址 http://holys.im/2016/09/20/go-get-in-gitlab/

据此 issue,gitlab 7.8 就开始支持 go get private repo。

假设 gitlab 服务是: mygitlab.com

使用方式:

$ go get -v mygitlab.com/user/repo

如果 mygitlab.com 不支持 https, 还得加上 -insecure 参数

$ go get -v -insecure mygitlab.com/user/repo

但是 -insecure 参数是 go 1.5 以后才有的,所以如果低于 1.5 版本,赶紧升级一下吧。

默认需要输入用户名和密码,比较繁琐。 由于 go get 底层实际还是用了 git 去操作。可以配置 .gitconfig 使之用 http => ssh 的访问方式 (个人感觉就是重写了 url)

$ git config --global url."git@mygitlab.com:".insteadOf "http://mygitlab.com/"

// 其实就是在 .gitconfig 增加了配置

$ cat ~/.gitconfig

[url "git@mygitlab.com:"]

insteadOf = http://mygitlab.com/

注意: git@mygitlab.com: 后面有个冒号 :, 且 http://mygitlab.com 后面有 /

另外: url.”aaa”.insteadOf “bbb” 是个相当有用的技巧,对 github 同样适用。

$ git config --global url."git@github.com:".insteadOf "https://github.com/"

$ cat ~/.gitconfig

[url "git@github.com:"]

insteadOf = https://github.com/

这样 git clone https://github.com/golang/go.git 就变成 git clone git@github.com:golang/go.git , 免去输入账号密码的烦恼。

总结:

gitlab >= 7.8

go >= 1.5 (如果 gitlab 不支持 https)

git url insteadOf

参考:

go get如何下载私有仓库

因为工作需要,我们用得都是自己搭建得git仓库,go get无法下载私有仓库,

go get -insture 倒是可以下载,但是在go mod下无法自动

网上看了一大堆文章,各种方法说得乱七八糟,不顶用,最终解决方法如下

1、代码仓库一定要使用https(非常重要)

2、使用https后go get就自动会给你提示了

fatal: could not read Username for 'https://xxx.com': terminal prompts disabled

If this is a private repository, see https://golang.org/doc/faq#git_https for additional information.

看到重点没有,go开发人员的工作还是做得比较仔细,连文档地址都告诉我们了,哈哈????

打开https://golang.org/doc/faq#git_https查看

这一步是不是感觉又撞墙了,无法打开????,但是没关系,我们有 godoc,执行

godoc -http :1088

浏览器输入http://localhost:1088/doc/faq#git_https

查看文档如下

Companies often permit outgoing traffic only on the standard TCP ports 80 (HTTP) and 443 (HTTPS), blocking outgoing traffic on other ports, including TCP port 9418 (git) and TCP port 22 (SSH). When using HTTPS instead of HTTP, git enforces certificate validation by default, providing protection against man-in-the-middle, eavesdropping and tampering attacks. The go get command therefore uses HTTPS for safety.

Git can be configured to authenticate over HTTPS or to use SSH in place of HTTPS. To authenticate over HTTPS, you can add a line to the $HOME/.netrc file that git consults:

machine github.com login USERNAME password APIKEY

总结这段话就是说在 你的用户根目录下的.netrc文件加上git仓库登录账号就行了,是不是很简单

echo "machine 仓库地址 login 用户名 password 密码" > ~/.netrc

ok,再次执行go get 一切顺利

作者:悟道人

链接:https://www.jianshu.com/p/e48621f71e9b

来源:简书

著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。