golang私有仓库gomod配置

1,131 阅读1分钟

引言

微服务之间的业务实现,服务之间一般会使用gRPC的方式相互调用。就会涉及到私有仓库的包引用。

问题

gitlab.*****.com/*****/****/internal/biz imports
	gitlab.*****.com/*****/m****/api/***/v1: gitlab.*****.com/*****/m****@v0.0.0-20230224074250-******e5775c: invalid version: git ls-remote -q origin in /go/pkg/mod/cache/vcs/*******90877400b8c10f33b557d3d0006e377b45e2c7840a866e********: exit status 128:
	fatal: could not read Username for 'https://gitlab.*****.com': terminal prompts disabled
Confirm the import path was entered correctly.
If this is a private repository, see https://golang.org/doc/faq#git_https for additional information.

解决

go 官方建议

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
For GitHub accounts, the password can be a personal access token.

Git can also be configured to use SSH in place of HTTPS for URLs matching a given prefix. For example, to use SSH for all GitHub access, add these lines to your ~/.gitconfig:

[url "ssh://git@github.com/"]
	insteadOf = https://github.com/

私有仓库拉取

go env -w GOPRIVATE=gitlab.*****.com

vim ~/.gitconfig

[url "git@gitlab.*****.com:"]
    insteadOf = https://gitlab.*****.com/

GOPRIVATE 配置私有库下的包不经过代理下载,不经过SUMDB验证.但GONOPROXY和GONOSUMDB均为none,意味着所有module,不管是公共的还是私有的, 都要经过代理下载。

gitlab runner

- GOPRIVATE=gitlab.*****.com
- GIT_USER=your_username
- GIT_TOKEN=your_access_token
- git config --global url."https://$GIT_USER:$GIT_TOKEN@$GOPRIVATE".insteadOf "https://$GOPRIVATE"
  1. 设置私有仓库的hostname :gitlab.*****.com
  2. 设置私有仓库username :your_username
  3. 设置gitlab access token :gitlab->Settings->Access Token,创建个人访问令牌,权限建议选择只读(read_repository)
  4. 配置git config :使用accesss token 验证私有仓库身份,避免密码校验。

Dockerfile

# go proxy
ARG GOPROXY=https://goproxy.cn,direct
# gitlab 私用仓库domain
ARG GOPRIVATE=gitlab.*****.com
# gitlab 仓库username
ARG GIT_USER=your_username
# gitlab 创建access-token
ARG GIT_TOKEN=your_gitlab_access_token
# 设置gitlab-access-token
RUN git config --global url."https://$GIT_USER:$GIT_TOKEN@$GOPRIVATE".insteadOf "https://$GOPRIVATE"