Tags: #go #dependencies
Copied verbatim from https://brokencode.io/how-to-use-local-go-modules-with-golang-with-examples/ so all credit goes to that author. I’m just gisting this content for my own future reference so I don’t have to go locate it again.
So first we simply have to convert all of our directories into go modules. For that we need to add a go.mod at the root of every directories. Then inside of that go.mod give them whatever name that we want as module name. but bear in mind that it has to be an url. In my example I put this:
module example.org/hello
in the go.mod for the hello directory
module example.org/utils
in the go.mod for the utils directory
The import makes a bit more sense now huh ? but we are not done yet.
This is where the magic happens, go.mod files have a few keywords that can be very useful, one of them is replace what replace does is that it takes a module path (eg : example.org/hello) and replaces it with a direct or relative path.
here’s the syntax for the replace keyword :
replace url.com/of/the/module => /direct/path/to/files
Note that replace also works with relative paths.
module example.com/localmodexample
go 1.13
require (
example.org/hello v0.0.0
example.org/utils v0.0.0
)
replace (
example.org/hello => ./hello
example.org/utils => ./utils
)
Usually go module dependencies work with versions, so to use local go modules with golang you have to set v0.0.0
Finally after the require, I just tell the compiler that those urls are local and can be found in the same directory under ./hello and ./utils. The great thing about this main go.mod file is that now even the utils module will know where to find the hello module because the url have been replaced.