Importing Unpublished Local Go Modules/Packages Into Your Codebase

If you’ve used Golang in its early days, then you’re used to putting all your codes in $GOPATH with its publication location as the path inside $GOPATH/src such as $GOPATH/src/github.com/m4hi2/pkg. And you’re accustomed to importing that package by using import "github.com/m4hi2/pkg" inside your go code. In recent versions of go, this behavior no longer works.

If you now, try to import as above, it won’t work and your lib won’t be imported. If you try to use go get github.com/m4hi2/pkg then it’ll try to download from your GitHub repo, which is fine if you’ve published the project to the internet but it will fail if the repo is unpublished and it’ll only download from the point the repo is updated which might not what you want since you might have updated your local copy.

So, how do you force go 1.19 to use your local package? Turns out, there are few ways. You can either use Go Workspace or you can use a replace directive in your go mod. I’ll discuss the replace directive way here, since if you’re publishing or deploying your codebase, all of your libraries should be accessable.

To use the local redirect for a pakcage, simply use the following command:

go mod edit --replace=github.com/m4hi2/pkg=../pkg <path to your lib in your filesystem>

go get github.com/m4hi2/pkg

This scenario is very useful when you’re developing a library and using it at the same time. Always remeber to remove your redirects from your go.mod file before publishing your code. Since it relies on having the files on the exact places you’ve described.

If you’ve any questions or problems following this, feel free to reach out to me on my LinkedIn or email me at [email protected].
Thanks for reading. 🙂