go,

Pull Go modules from private repositories

Dec 20, 2022 · 1 min read · Post a comment

One of the first struggles with Go, was when I wanted to have a private repo for the app. Apparently, if you run go get, Go uses Git to pull the specific versions of your dependency packages. As with any private repo, you need to be authenticated. This is how you do it.

Prerequisites

  • Go(lang)
  • Private Git repository

Solution

I’ll use GitHub as an example, but basically it should work with any other popular Git hosting platform including GitLab and Bitbucket.

Step 1. Make sure you get a GitHub personal access token.

Step 2. Once that’s done, save it in a secure place. Next, export it as an environment variable.

export GITHUB_TOKEN=<some_token>

Step 3. Update Git to use the basic auth url:

git config --global url."https://$GITHUB_TOKEN:[email protected]/".insteadOf "https://github.com/"

or:

git config --global url.https://$GITHUB_TOKEN@github.com/owner/repo.git.insteadOf "https://github.com/"

Step 4. Verify it, by running: go get again.

There are other alternate solutions too, such as SSH and .netrc, but honestly haven’t tried them yet. For the sake of complexity, I keep with the basics.

You can even implement it as a part of Dockerfile, a CI/CD pipeline and what not. But, beware. It’s considered a bad practice if you hardcode any secret / token in a Dockerfile, or even anywhere that’s Git-versioned, since you’ll most probably compromise your private repo. So, from security standpoint, you got two options:

  • Hardcode it, but make sure the access token permissions are read-only (the easier, worse solution).
  • Pull the token from some cloud vault, or any secret management tool (better, probably the best solution).

Conclusion

That worked for me though. But, if you are still having the same issue, feel free to leave a comment below. And, in case you found this tutorial useful, follow our official channel on Telegram.