When working with Go we are (and must) using modules. They’re a fantastic way to organize our code and our dependencies without the restriction of putting everything inside of our GOPATH.
Let’s suppose that we’re working with 2 modules and the first one depends on the second one, as follows:
Now, if we take a look at our go.mod in cool-api we can see something like this:
module github.com/federicoleon/cool-api go 1.15 require ( github.com/federicoleon/cool-library v0.1.0 )
When working with these two modules, we’ll have the need to make changes in cool-library and use them in cool-api to verify that everything is working as expected.
We have two ways of doing this:
- Make the changes in cool-library, commit the changes to Github, create a new tag and then update our cool-api go.mod to use the new dependency.
- Point our cool-api dependency to use our local cool-library, make all of the changes and once we’re happy with the result, do as defined in step 1.
The advantage that we have when using local Go modules is that we don’t need to create new tags (versions) on Github that we’re never going to use because they could (and they will certainly) have logic errors, compilation errors or debugging lines that we need to get rid of.
Introduction to replace
We can use the replace keyword inside of our go.mod definition to tell to the module that it should be using our local module instead of the one available on Github:
module github.com/federicoleon/cool-api go 1.15 replace github.com/federicoleon/cool-library => /mnt/disk_b/workspaces/cool/cool-library require ( github.com/federicoleon/cool-library v0.1.0 )
What we’re saying with our replace definition is basically “fetch this module from this location“. If you pay attention to this, it becames pretty obvious that inside of /mnt/disk_b/workspaces/cool/cool-library (the location of our local module) we must have a valid go.mod file.
After updating our go.mod file we can now sync our module’s dependencies by using our terminal, go to the folder where we have our go.mod file and running:
go mod tidy
Of course, you don’t want to push your go.mod nor go.sum changes to Github when you have a replace directive pointing to a local dependency. This is for local development only.
I hope this will help you with your local development and reduce the amount of unnecesary versions you have on Github!
See you next time!