Using private Git repository in Golang

该文章根据 CC-BY-4.0 协议发表,转载请遵循该协议。
本文地址:https://fenying.net/en/post/2025/02/08/using-private-git-repository-in-golang/

This article records my experience of installing and referencing code from a private Git repository in Golang.

When using the go get command to fetch code from a private (non-public access) Git repository, authentication issues or network isolation issues may prevent the go command from fetching the code.

To solve this problem, you need to solve two problems:

  1. Ensure that the go toolchain treats the specified domain as a private domain and does not access it through its public proxy (the go toolchain will check whether the specified repository is available through a public proxy sum.golang.org by default).

  2. Grant the access permission of the private repository to the go toolchain, whether through the HTTPS protocol or the SSH protocol.

1. Specify private domains

This is very easy that you can specify the private domains by setting the GOPRIVATE environment variable:

1export GOPRIVATE=git.domain1.com,git.domain2.com

It is recommended to add it to ~/.bash_profile.

After configuring this, the go command will directly access the code from these domains without going through the proxy.

2. Grant access permission to the go toolchain

Since the go command actually fetches code through the git command, as long as the git command can access the private repository, so can the go command.

Let’s say when you execute the go get your-domain.com/username/repo-name command, the go command will fetch the code through the following command:

1git clone https://your-domain.com/username/repo-name.git

If you want to let it access the repository through the SSH protocol, you can configure the git command to replace the URL from https to ssh protocol:

1YOUR_DOMAIN=your-domain.com
2
3git config \
4    --global url."git@$YOUR_DOMAIN:".insteadOf "https://$YOUR_DOMAIN/"

This command forces the git command to replace https://$YOUR_DOMAIN/ with git@$YOUR_DOMAIN:, for example, replace https://your-domain.com/username/repo-name.git with [email protected]:username/repo-name.git.

Of course, if you choose to use the HTTPS protocol but need authentication, you can use a similar method to add authentication information to the URL:

1YOUR_DOMAIN=your-domain.com
2YOUR_USERNAME=your-username
3YOUR_PASSWORD=your-password # maybe an API Token
4
5git config \
6    --global url."https://$YOUR_USERNAME:$YOUR_PASSWORD@$YOUR_DOMAIN/".insteadOf "https://$YOUR_DOMAIN/"

Alright, that’s all.

comments powered by Disqus

Translations: