Go 编译时使用私有仓库

建议点击 查看原文 查看最新内容。

原文链接: https://typonotes.com/posts/2025/03/27/go-build-with-private-bitbucket/

使用私有仓库, 无论如何都需要配置 GOPRIVATE 变量

1
2
export GONOSUMDB=git.example.com  # comment this line if GOPROXY isn't set
export GOPRIVATE=git.example.com

1. 本地开发

在本地开发的时候, 通常使用 ssh 协议进行权限验证。

例如 clone 时地址如下格式如下

1
2
ssh://[email protected]/ ...
https://git.example.com/scm/ ...

则执行如下命令替换验证方式

$ git config --global url.ssh://[email protected]/.insteadOf https://git.example.com/scm/

2. 容器中个编译

在容器中, 通常可以使用 HTTPS Token

$ git config --global url.https://${GIT_CI_SECRET}@git.example.com/scm/.insteadOf https://git.example.com/

注意 如果 username, password 中有特殊符号, 例如 @ 或者 / 等, 需要进行 URL 编码

@ -> %40
/ -> %2F
: -> %3A

Dockerfile

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
# language=golang
## IMAGE ARGS

ARG BASE_IMAGE=golang:1.23
FROM ${BASE_IMAGE} AS env
ENV GOPRIVATE=git.example.com
ENV GONOSUMDB=git.example.com

FROM env AS builder

# 注入 Token
ARG GIT_CI_SECRET
RUN [ -n ${GIT_CI_SECRET} ] && git config --global url.https://${GIT_CI_SECRET}@git.example.com/scm/.insteadOf https://git.example.com/

WORKDIR /go/src
ADD . .
RUN make install

FROM alpine:3.12 AS runtime
COPY --from=builder /go/bin/webapp /usr/bin/webapp
EXPOSE 3000
ENTRYPOINT ["/usr/bin/webapp"]

docker build 执行编译的景象打包的时候, 使用 --build-arg 传入即可。

1
2
3
4
5
$ docker build \
    -t example.com/ax-demo-api \
    -f Dockerfile.token \
    --build-arg GIT_CI_SECRET=username:password \
    .