How to use private repositories in GO projects
Overview:
In this guide, we’ll explore how to utilize private repositories in your Go projects. We’ll cover the steps needed to configure your Go environment to seamlessly integrate private repositories.
Prerequisites:
- Ensure you have Go installed on your system.
- You should have ssh keys setup linked to your Github account.
Go Projects:
- We have 2 Go projects/ repositories here.
- The Go private repository you want to use.
- The new Go project you want to use the private repository in.
- Eg: Using a private cleaner repo in a new data pipeline Go project.
Step-by-Step Guide
Step 1. Get the private repository path:
- Begin by navigating to your private repository’s go.mod file.
- Here you will find the full path to your private repository, which is essential for the import process.
- The path usually follows the format “github.com/user/private_repo”
Step 2: Configure Go for Private Repositories:
To let Go know to use your private repo instead of fetching it from public servers we export GOPRIVATE variable with the full repository path.
export GOPRIVATE="github.com/username/private_repo"
Step 2: Import the private repository in your new project:
Open any Go file in your new project where you need to import your private package. For example, if you’re working with a file named test.go, you would include the following import statement at the top:
// eg: test.go file in the new project
package main
import (
"fmt"
"github.com/username/private_repo"
)
3. Use SSH for authentication:
Run these command in terminal, to use ssh instead of http while cloning the repos
git config --global url."git@github.com:".insteadOf "https://github.com/"
Step 4: Tidy Up Your go.mod File:
This command cleans up your project’s go.mod file, adding the private repository you’re importing, updating the go.sum file, and downloading the necessary dependencies to your system.
Step 5: Run Your Go File
You can access any function in the new project by using the package name of the imported repo followed by function name.
eg: package_name.DoSomething()
// File: test.go
package main
import (
"github.com/user/private_repo"
)
func main() {
private_repo.DoSomething()
}
// run file using -> go run test.go
Conclusion:
By following these steps, we’ve successfully imported a private Go repository into our project.
For more insights on Generative AI, Python, Systems, and indie product development, follow my journey.
Happy coding, and may your Go projects run smoothly and securely!!