golang项目引用GitHub私有仓库module


1.创建go module项目

module的名字假设为go-test

module项目创建成功后,将go.mod文件中的 module "go-test" 修改成

1
module "github.com/tonglin0325/go-test"

避免引用的时候go get报错,如下

1
2
3
4
go get github.com/tonglin0325/go-test@latest
go: github.com/tonglin0325/go-test@latest (v1.0.0) requires github.com/tonglin0325/go-test@v1.0.0: parsing go.mod:
    module declares its path as: go-test
            but was required as: github.com/tonglin0325/go-test

在module中写好代码后上传到github上,并在github上给项目打上tag

如果GitHub repository设置成public的话,此时就可以使用如下命令引用这个module了

1
2
3
➜  /Users/lintong/coding/go/gin-template git:(main) ✗ $ go get github.com/tonglin0325/go-test@latest
go: downloading github.com/tonglin0325/go-test v1.0.1
go: added github.com/tonglin0325/go-test v1.0.1

2.引用私有仓库的go module

1.Github私有仓库

如果使用的私有仓库是github,则电脑配置了github的私钥的话,可以直接使用go get命令来引用私有仓库的依赖

如果没有设置的话,则可以使用github的token来下载依赖

在github用户settings的Developer settings中创建一个token,token name假设为goland

指定go module的项目,并设置contents设置为read only

创建后获得token

重新设置github使用账号+token来拉取依赖

1
git config --global url."https://tonglin0325:your_token@github.com".insteadOf "https://github.com"

查看git配置是否添加成功

1
git config --global -l

如果添加错误可以unset之后再重新set

1
git config --global --unset xxx

指定拉取go-test依赖的时候使用私有仓库

1
go env -w GOPRIVATE=github.com/tonglin0325/go-test

查看go环境变量

1
go env

如果设置失败,可以删除后再添加

1
go env -u GOPRIVATE

最后使用go get命令引用依赖

1
go get github.com/tonglin0325/go-test@latest

2.Gitlab私有仓库

如果使用的私有仓库是gitlab,则可以参考如下文档,在 ~/.netrc 文件中配置gitlab的access token

Use a project as a Go package

然后使用如下命令来get依赖

1
GOPRIVATE=gitlab.xx.com go get gitlab.xx.com/xx/xx

 

posted @   tonglin0325  阅读(130)  评论(0编辑  收藏  举报
努力加载评论中...
点击右上角即可分享
微信分享提示