Go拉取私有仓库的问题

2021/6/28 gopackage manager

现在项目开发有很多私有仓库,直接git clone的方式使用,不是怎么方便。

查询go源码发现go get支持的协议除了https还支持git+ssh, bzr+ssh, svn+ssh, ssh

$GOSRC/cmd/go/internal/get/vsc.go

var defaultSecureScheme = map[string]bool{
	"https":   true,
	"git+ssh": true,
	"bzr+ssh": true,
	"svn+ssh": true,
	"ssh":     true,
}
1
2
3
4
5
6
7

# 简单 - 直接使用git/ssh方式

直接在go get gitlab.com/****/****时,在后面加上.git, go会自动使用git/ssh的方式拉取git仓库.

注意: 正常的拉取方式,会生成$GOPATH/git.gitlab.com/****/****目录接口, 使用.git方式拉取会生成$GOPATH/gitlab.com/****/****.git的目录接口

# 修改配置的方式

  1. 私有仓库一般没方法sum校验,我们先把sum校验去除掉

配置环境变量使拉取代码不走代理与sum校验

export GOPRIVATE="gitlab.com"
1

这个配置后, 拉取仓库,可以发现gitlab.com/user***/repo, 这种私有仓库我们能正常的拉取, 但是类似gitlab.com/gourp1/gourp2/repo不能正常拉取,

使用go get -v gitlab.com/gourp1/gourp2/repo后能发现, go认为仓库的真实地址是gitlab.com/gourp1/gourp2,并不是gitlab.com/gourp1/gourp2/repo

这个问题我们通过查看源码依旧能发现 $GOSRC/cmd/go/internal/get/vsc.go

var vcsPaths = []*vcsPath{
	// Github
	{
		prefix: "github.com/",
		regexp: lazyregexp.New(`^(?P<root>github\.com/[A-Za-z0-9_.\-]+/[A-Za-z0-9_.\-]+)(/[\p{L}0-9_.\-]+)*$`),
		vcs:    "git",
		repo:   "https://{root}",
		check:  noVCSSuffix,
	},

	// Bitbucket
	{
		prefix: "bitbucket.org/",
		regexp: lazyregexp.New(`^(?P<root>bitbucket\.org/(?P<bitname>[A-Za-z0-9_.\-]+/[A-Za-z0-9_.\-]+))(/[A-Za-z0-9_.\-]+)*$`),
		repo:   "https://{root}",
		check:  bitbucketVCS,
	},
    // .....
    {
		regexp: lazyregexp.New(`(?P<root>(?P<repo>([a-z0-9.\-]+\.)+[a-z0-9.\-]+(:[0-9]+)?(/~?[A-Za-z0-9_.\-]+)+?)\.(?P<vcs>bzr|fossil|git|hg|svn))(/~?[A-Za-z0-9_.\-]+)*$`),
		schemelessRepo: true,
	},
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
  1. 配置获取仓库授权

配置~/.netrc(window中配置~/_netrc)完成gitlab授权,获取真实的git路径

machine gitlab.com login 账号 password 密码或者访问令牌
1

使用访问令牌请勾选api的权限

  1. 修改git拉取https替换 ssh

我们知道go get默认会使用https的方式拉取代码,由于git-remote-https走的验证是用户名,密码, 不怎么方便,我们来通过更改git的全局配置来使用ssh的方式拉取。 下面是配置https转换为ssh的命令

git config --global url."git@gitlab.com:".insteadOf https://gitlab.com/
1

# 参考资料

最后更新时间: 2025/2/27 19:03:05