DEV Community

ADITYA OKKE SUGIARSO
ADITYA OKKE SUGIARSO

Posted on

Create Golang private package

#go

note:

this article based on chatGPT generated content and already tested by me

step:

1. Host your repo somewhere private
E.g. GitHub/GitLab/Bitbucket private repo at

# git
git@github.com:your-org/private-pkg.git

# bitbucket
git@bitbucket.org:your-org/private-pkg.git
Enter fullscreen mode Exit fullscreen mode

2. Initialize the module
In your local checkout:

cd private-pkg
go mod init github.com/your-org/private-pkg
Enter fullscreen mode Exit fullscreen mode

This creates a go.mod with:


module github.com/your-org/private-pkg

go 1.21
Enter fullscreen mode Exit fullscreen mode

3. Write your code
Example foo.go:

package privatepkg

// Hello returns a greeting.
func Hello(name string) string {
    return "Hello, " + name
}
Enter fullscreen mode Exit fullscreen mode

Commit & push:

git add .
git commit -m "initial private-pkg module"
git push origin main
Enter fullscreen mode Exit fullscreen mode

4. Tag a version (Semantic Versioning)
Decide on your first release, e.g. v0.1.0:

git tag v0.1.0
git push origin v0.1.0
Enter fullscreen mode Exit fullscreen mode

Go tooling will recognize that tag as the module’s v0.1.0 version.
5. Tell Go which repos are private
On any machine that will consume your private module, set:

# mark your entire Bitbucket org as private
go env -w GOPRIVATE=bitbucket.org/your-org/*

# mark your entire Github org as private
go env -w GOPRIVATE=github.com/your-org/*
Enter fullscreen mode Exit fullscreen mode
  • GOPRIVATE - list of glob patterns of module path prefixes that should be considered private. Acts as a default value for GONOPROXY and GONOSUMDB.

6. Consume the module in another project
In your client repo:

go mod init example.com/your-app
go get github.com/your-org/private-pkg@v0.1.0
Enter fullscreen mode Exit fullscreen mode

Import and use:

import "github.com/your-org/private-pkg"

func main() {
    fmt.Println(privatepkg.Hello("World"))
}
Enter fullscreen mode Exit fullscreen mode

Then:

go build

Enter fullscreen mode Exit fullscreen mode

7. Releasing updates

  • Make changes in private-pkg, bump code.
  • Update go.mod if you need to require newer dependencies.
  • Commit and git tag v0.2.0 (or v1.0.0 when you make a breaking change).
  • git push origin main --tags
  • In your app: go get github.com/your-org/private-pkg@v0.2.0

Top comments (0)