Golang mod使用GitLab私有仓库

介绍:在Go开发过程中我们经常使用的包来源都是GitHub,但是在内部开发中某些内部的包不可能放到GitHub公共仓库中,大部分企业会选择放在GitLab来使用,这里就介绍Golang如何使用GitLab当做私有仓库

下面所示go.mod中,以git.putianhui-local.cn开头的地址,是我们的GitLab私有仓库,这里混合使用了公共包内部私有包。

1
2
3
4
5
6
7
8
9
10
11
module go_test

go 1.16

require (
git.putianhui-local.cn/ops/ops-test v0.0.0-20220802013626-1e9ec900c37b // 这个是内部私有包
github.com/google/uuid v1.3.0
github.com/hashicorp/errwrap v1.1.0 // indirect
github.com/tidwall/gjson v1.14.1
golang.org/x/net v0.0.0-20220615171555-694bf12d69de // indirect
)

我这里内部的GitLab站点http协议的没有配置httpsssh协议正常的,下面配置如何从私有GitLab获取依赖。

1、首先你本地电脑生成ssh的秘钥,将公钥上传到你GitLab平台上,先实现本地通过ssh协议免密拉取项目代码。

2、修改go env的配置

1
2
3
4
5
6
7
8
9
10
11
// 配置开启gomod
go env -w GO111MODULE="on"
// 配置GoMod私有仓库地址
go env -w GOPRIVATE="git@git.putianhui-local.cn"
// go env -w GOPRIVATE="git.putianhui-local.cn"
// 配置不加密访问的仓库地址
go env -w GOINSECURE="git.putianhui-local.cn"
// 配置不使用代理的仓库地址
go env -w GONOPROXY="git.putianhui-local.cn"
// 配置不验证包的仓库地址
go env -w GONOSUMDB="git.putianhui-local.cn"

3、配置Git下git.putianhui-local.cn这个仓库不以http方式拉取。

命令方式设置

1
git config --global url."git@git.putianhui-local.cn:".insteadOf "https://git.putianhui-local.cn"

你也可以直接修改git的配置文件添加,和上面二选一即可。

1
2
3
4
$ vim ~/.gitconfig
# 后面添加以下内容
[url "git@git.putianhui-local.cn:"]
insteadOf = https://git.putianhui-local.cn

4、拉取一个GitLab私有仓库依赖验证

在我GitLab上有一个叫做ops-test的仓库,这个仓库下有一个rand.go文件,里面有个测试的函数这里测试一下。

GitLabops-test的仓库地址:git.putianhui-local.cn/ops/ops-test

go.mod文件内容

1
2
3
module git.putianhui-local.cn/ops/ops-test

go 1.16

rand.go文件内容

1
2
3
4
5
6
7
package stringutil

import "fmt"

func RandString() {
fmt.Println("xiaopu")
}

go get获取下这个私有仓库的依赖验证

1
2
# 此时你会发现下载成功了。
$ go get git.zxkw-local.com/ops/ops-test

示例验证代码

1
2
3
4
5
6
7
8
9
package main

import (
"git.zxkw-local.com/ops/ops-test"
)

func main() {
stringutil.RandString()
}

运行后结果

1
xiaopu