DEV Community

Thomas Ersfeld
Thomas Ersfeld

Posted on • Edited on • Originally published at tersfeld.github.io

Private Go modules on a privately hosted github instance

Go modules are highly dependant on github to fetch modules, it is fine in most cases as tons of modules are available publicly on it.

It can get tricky when you got your private Go libraries that are not hosted on github.com. Here is a simple solution to pull them from your git instance without breaking the fetching of public dependencies on Github.

This will only work on Go 1.13 with the introduction of GOPRIVATE env.

Create your private lib

Create a simple private repo at your instance with that form:
your.hosted.github.instance.com/my_organization/privatelib

Add one file containing a sample Go file, named for example, lib.go:

package privatelib

import "fmt"

func MyPrivateCall() {
  fmt.Println("My super secret lib!")
}

Don't forget the capital letter at the start of your exported resources (functions, enums, structs...) to mark them as exported, in this example MyPrivateCall() will be exported.

Generate a token in your github instance

You can generate tokens with this direct link : https://your.hosted.github.instance.com/settings/tokens/new

Always get the least privileges needed for your token (can read private repos).

Use your private lib in your main project

In your main Go project, you can now import your private lib at the top of the file:

package api

import (
    "fmt"
    //...

    privatelib "your.hosted.github.instance.com/my_organization/privatelib"
)

// ...


func myApiHandler() {
    privatelib.MyPrivateCall()
}

We need to indicate to go mod to inject our credentials when a module hosted on https://your.hosted.github.instance is parsed in go.mod :

go env -w GOPRIVATE=your.hosted.github.instance
go config --global url."https://your_username:your_token@your.hosted.github.instance.com".insteadOf / "https://your.hosted.github.instance"

Replace your_token by the token generated in step 2.

Now we fetch and build :

go mod download
go build ...

I hope that was useful :)

Top comments (0)