Use a Local Version of a Library in Go

I have a couple of projects in Go where I need to work with a branch that isn’t the released version of a library that my code depends on. This happens when I’m the developer of the library and an application to use it, or when I’m a contributor to the library so I have my own fork and will want to check out branches to submit or test patches. Go has a pretty need way to allow this: using the replace keyword in the go.mod file.

Set up Git Remotes

Start by cloning the library into the place in your GOPATH that this library would usually live. In this example, I’m using the magicmonkey/go-streamdeck library (lots more to write about this library so watch this space) so it lives at $GOPATH/src/github.com/magicmonkey/go-streamdeck and is a clone of that main GitHub repo at https://github.com/magicmonkey/go-streamdeck.

Since I’m also contributing changes to this library, I forked the GitHub project and have my own copy (that I can commit to branches on) at https://github.com/lornajane/go-streamdeck. Grabbing the clone URL, I added this repo as another remote to the existing go-streamdeck library:

git remote add lornajane [paste clone URL]

Pro-tip: git does not check this remote exists or that you can access it, it just believes you and stores the URL. Run git fetch lornajane (or whatever you named your remote) to actually link with it.

Now the library is all set up, and I need to configure my own project to use the local version of the code, not look for the latest public release.

Configure Go.Mod to use Local Dependency

In the go.mod file for the project that uses this library, the first few lines look like this:

module github.com/lornajane/streamdeck-tricks

go 1.14

replace github.com/magicmonkey/go-streamdeck => /home/lorna/go/src/github.com/magicmonkey/go-streamdeck

… then the usual require block is below.

This setup means that changes I make on disk are reflected immediately in my project, I don’t even need to commit. For creating and testing patches to a library, it’s excellent and I have to look up the syntax every time so it’s here for fast(er) reference!

Edit: Completely failed to link this excellent post on using replace from Pam Selle which covers the same stuff but better.


Also published on Medium.

Leave a Reply

Please use [code] and [/code] around any source code you wish to share.

This site uses Akismet to reduce spam. Learn how your comment data is processed.