Import private module from GitHub repository

$ mkdir demo_lib
$ cd demo_lib
## demo_lib.go
package demo

import "fmt"

func Hello() {
	fmt.Println("Hello")
}

  • install go module
$ go mod init github.com/<username>/<repo>
...
go: creating new go.mod: module github.com/<username>/<repo>
go: to add module requirements and sums:
        go mod tidy
  • go mod tidy
$ go mod tidy
  • create private git repo and init
$ git init
$ git add -A
$ git commit -m "first commit"
$ git branch -M main
$ git remote add origin https://github.com/<username>/<repo>.git
$ git push -u origin main

Test go get from private repo

$ go get github.com/<username>/<repo>
...
go: finding module for package github.com/<username>/<repo>
using_lib imports
        github.com/<username>/<repo>: cannot find module providing package github.com/<username>/<repo>: module github.com/<username>/<repo>: git ls-remote -q origin in /Users/xxx/project/golang/src/pkg/mod/cache/vcs/93548d0d7cfb6899180c0009764ea6937175944f7ac282c5f42f814577389a91: exit status 128:
        remote: Repository not found.
        fatal: repository 'https://github.com/<username>/<repo>' not found

Solution

$ go env -w GOPRIVATE=github.com/<username>
$ git config --global url."https://<username>:<password | access_token from github>@github.com".insteadOf "https://github.com"
$ go get github.com/<username>/<repo>
...
go: finding module for package github.com/<username>/<repo>
go: found github.com/<username>/<repo> in github.com/<username>/<repo> v0.0.0-20210330081440-a00e64fd24d2

  • Demo project for use module from github private repo
# example
# main.go
package main

import demo_lib "github.com/workjaedsada3/demo_lib"

func main() {
	demo_lib.Hello()
}
$ go run .
...
Hello