模块极大地改善了Golang的依赖管理过程。正确配置所有内容后,很容易就能够从公共存储库获取特定版本的Go软件包。一个典型的go.mod:
go.mod
module github.com/samplerepo/sampleproject
go 1.14
require (
github.com/pkg/errors v0.8.0
github.com/spf13/cobra v0.0.4
github.com/spf13/viper v1.3.2
)
但是在实际项目中我们不可能把所有的软件包都放在公共存储库中,那么我们应该如何导入私有库的Go软件包呢?事实上,非常简单:确保我们的Go安装程序可以访问私有的Git库。Go使用Git提取依赖项的指定版本。 因此,无论Go运行在哪里(例如Docker容器或笔记本电脑),git配置都必须具有适当的凭据才能访问任何私有存储库。我们可以通过git config命令进行相应的配置,git config将再.gitconfig文件中放置一个条目,该条目告诉git每当需要访问标准URL时都使用凭据格式的URL。 因为这些条目都是纯文本存储的,所以在此我们使用个人访问令牌而不是密码。
- BitBucket
bitbucket.sh
git config \
--global \
url."https://${bitbucket_id}:${bitbucket_token}@privatebitbucket.com".insteadOf \
"https://privatebitbucket.com"
- Github
github.sh
git config \
--global \
url."https://${user}:${personal_access_token}@github.com".insteadOf \
"https://github.com"
- Gitlab
gitlab.sh
git config \
--global \
url."https://oauth2:${personal_access_token}@privategitlab.com".insteadOf \
"https://privategitlab.com"
#or
git config \
--global \
url."https://${user}:${personal_access_token}@privategitlab.com".insteadOf \
"https://privategitlab.com"
基于docker的构建例子:
Dockerfile
# ---------------------------------------------------------------------
# The first stage container, for building the application
# ---------------------------------------------------------------------
FROM golang:1.12.1-stretch as builder
COPY . /app
# Add the keys
ARG bitbucket_id
ENV bitbucket_id=$bitbucket_id
ARG bitbucket_token
ENV bitbucket_token=$bitbucket_token
WORKDIR /app/cmd/webapp
RUN git config \
--global \
url."https://${bitbucket_id}:${bitbucket_token}@privatebitbucket.com/".insteadOf \
"https://privatebitbucket.com/"
RUN GIT_TERMINAL_PROMPT=1 \
GOARCH=amd64 \
GOOS=linux \
CGO_ENABLED=0 \
go build -v --installsuffix cgo --ldflags="-s" -o myapp
# ---------------------------------------------------------------------
# The second stage container, for running the application
# ---------------------------------------------------------------------
FROM alpine:3.8
COPY --from=builder /app/cmd/webapp/myapp /app/myapp
WORKDIR /app
ENTRYPOINT ["/myapp"]
进行此设置的另一种方法是使用SSH密钥进行连接,并按如下所示设置.gitconfig,以确保每次都使用SSH:
github-ssh.sh
git config \
--global \
url."git@github.com".insteadOf \
"https://github.com"
需要注意的一点是,如果我们是使用GOPROXY下载依赖包,需要通过GOPRIVATE设置私有库地址不用proxy,例如: export GOPRIVATE="github.com/das-acc/*"