
In the world of Go development, modules have revolutionized dependency management. But what happens when you need to use private GitHub repositories as modules in your Go projects? This blog post will guide you through the process of setting up and using private GitHub repos as Go modules, ensuring secure and efficient development for your proprietary code.
Why Use Private GitHub Repositories as Go Modules?
Before we dive into the how, let’s briefly discuss why you might want to use private GitHub repositories as Go modules:
- Code Privacy: Keep proprietary code secure and separate from public repositories.
- Version Control: Benefit from Git’s version control while managing private dependencies.
- Collaboration: Share private modules within your team or organization.
- Dependency Management: Utilize Go’s module system for all your dependencies, public and private.
Step-by-Step Guide to Using Private GitHub Repos as Go Modules
Setting Up Your Private GitHub Repository
First things first, you need a private GitHub repository.
If you don’t already have one, create a new repository. Let’s assume you’ve already got one.
Initialize Your Module
Navigate to your project directory and initialize a new module:
1go mod init github.com/your-username/your-private-repo
Authenticate with GitHub
To authenticate with GitHub, you need to create a personal access token.
- Go to your GitHub settings.
- Click on “Personal access tokens.”
- Click on “Generate new token.”
- Give your token a name, select the appropriate scopes, and click “Generate token.”
Now, you can use the token to authenticate with GitHub.
1git config --global url."git@github.com:".insteadOf "https://github.com/"
Set up the credential store
Mac
1git config --global credential.credentialStore keychain
Linux
1git config --global credential.credentialStore gpg
Windows
1git config --global credential.credentialStore wincred
Set Up Environment Variables
We need to tell Go to treat our private repository as a private module to be able to pull from GitHub.
You can do this by setting the GOPRIVATE
environment variable:
1export GOPRIVATE=github.com/your-username/your-private-repo
If you have multiple organizations, you can use a wildcard to tell Go to ignore all repositories in a specific organization:
1export GOPRIVATE="github.com/your-username/*,github.com/your-organization/*"
Or, you can use go env -w
to tell Go to ignore the private repository when resolving modules:
1go env -w GOPRIVATE=github.com/your-username/your-private-repo
Use the Module in Your Project
Now you can fetch your private module like any other:
1go get github.com/your-username/your-private-repo
Conclusion
Remember, the key to success with private modules is proper authentication setup and careful management of your GOPRIVATE settings.
Happy coding!
Send me deets!
Get an update on new posts and events.
I promise, no spam of shady business!