Publishing and Using Private Go Modules

19 August 2023

In the following post we go over and show an example of publishing and using a Go module from a private Git repository.

Go modules are packaged in git repositories, versioned by git tags. This is also true for private git repositories, with just a few minor changes. Let’s look at how to publish and use a Go module from a private git repository.

Publishing Private Module

  • Module name is the same as the repository name
  • Commit and push module to private repository as usual
  • Tag and push tags: git tag "v0.1.0" && git push --tags

Using Private Module

  • You should already have git setup and have access to git clone the private repository with SSH. Provide private module credentials for SSH by adding the following to your .gitconfig because Go defaults to https://:
[url "ssh://[email protected]/"]
	insteadOf = https://github.com/
  • Add the private module to the GOPRIVATE environment variable. The variable is a comma-separated list of glob patterns.
export GOPRIVATE=github.com/sgloutnikov/example-greeter-secret
  • Create a new project to use this private module and run go mod download all or go mod tidy.

main.go

package main

import "github.com/sgloutnikov/example-greeter-secret"

func main() {
	greeter.SayHello()
	greeter.SayHey()
}

Resulting go.mod

module greeter-user

go 1.20

require github.com/sgloutnikov/example-greeter-secret v0.1.0

Run the project

$ go run main.go
Hello!
Hey!

comments powered by Disqus