Local Go Modules (Go 1.11+)
I’m developing a Go module for use in another application. How do I import a go module locally without having to push changes to something like GitHub while I am developing it?
I get this question asked of me fairly frequently, and the answer is pretty simple.
The Setup
The assumption in the example below is that you plan on pushing things to GitHub. This choice really doesn’t matter, it could internally hosted, but for ease of explaining things we will use GitHub.
Let’s say you are developing an application called my_app. The go.mod
file should look something like this to start with:
module github.com/luciddev13/my_app
go 1.18
Now as you are developing, you want to add some functionality, but realize this would be super useful as a separate module so that other projects may use it. We will call this my_module. This go.mod
file would look like this:
module github.com/luciddev13/my_module
go 1.18
Now, to import my_module into my_app you would add require github.com/luciddev/my_module v0.0.1
to your go.mod
file of my_app.
However, the go toolchain can’t find my_module because it really isn’t on GitHub.
To rectify this you can add a replace
directive to the go.mod
file of my_app to instruct the toolchain where to find the module. It should now look like this:
module github.com/luciddev13/my_app
go 1.18
require github.com/luciddev/my_module v0.0.1
replace github.com/luciddev/my_module v0.0.1 => local/path/to/my_module
A quick go mod tidy
will “download” the module to the cache, and you should be all set.
This also works for relative paths:
replace github.com/luciddev/my_module v0.0.1 => ../relative/path/to/my_module
Once you are satisfied with my_module and have uploaded it to GitHub, and tagged it with a version number, you can remove the replace
directive, and it will fetch it from GitHub.
The nice thing about this is that the code uses the same import regardless of where the code is located. So you can move it around your local filesystem, or upload it to a host1, and the code doesn’t have to change.
Hope this helps you in some small way.
Thanks for visiting.
-
I am using GitHub as an example here, but wherever you or your organization upload your Go modules will work as well. ↩