[Golang] How to import a package on the specific version

In Golang, when a package is imported, by default the codebase of the package’s default branch will be used by the caller project. However, sometimes we want to import a package’s specific branch codebase. For example, the specific version fixed a bug where we can’t wait until the repository maintainer merges the pull request.

So in this post, I will walk you through how to specify a package version in your Golang project. Let me take an example to help explain better.

Step by step guide

There are two repositories github.com/oscarzhou/foo and github.com/oscarzhou/models. Basically, models defines some interfaces and structures that will be used in foo.

The project foo imports models in its codebase like below.

package foo

import (
	"github.com/oscarzhou/models"
)

func main(){
	...
}

Now let’s say a main data structure has been changed in project models feature branch. Meanwhile, the project foo needs to reference the new structure updated in models for the new feature. Here is how we work it out:

1. Get the latest commit sha of the models feature branch

git log <branch_name>

You can find the sha in the first line of the output, like 213cb9ab4b5f53687f82e2a5d4567265a0081658.

2. Download the package with the specific commit sha in foo

go install github.com/oscarzhou/models@213cb9ab4b5f53687f82e2a5d4567265a0081658

It will output the corresponding pseudo-version of the package.

go: downloading github.com/oscarzhou/models v0.0.0-20220613031041-213cb9ab4b5f

3. Update the go.mod in foo

Locate the dependency of github.com/oscarzhou/models in go.mod file and replace the pseudo-version with the new one generated in step 2

4. Update the go.sum in foo

go mod tidy

Here it is. You can develop the new feature with the updated data struture in repository models.

Just note that when the model feature branch is merged, you’ll need to change the pseudo-version of dependency github.com/oscarzhou/models back to the default branch. Just do over again the above steps.

A more efficient way?

The above step by step guide shows you how to reference a third-party package on its specific commit version. However, it’s a bit tedious. Here is a more efficient way to do it.

Go to the directory where the go.mod file of github.com/oscarzhou/foo project is located. Run the command go get <package_name>@<commit_sha> as shown below, Go module will automatically update the go.mod and go.sum files for you. Yes, it replicates the exact actions performed in the above 2-4 steps automatically.

go get github.com/oscarzhou/models@213cb9ab4b5f53687f82e2a5d4567265a0081658

If this post helped you to solve a problem or provided you with new insights, please upvote it and share your experience in the comments below. Your comments can help others who may be facing similar challenges. Thank you!
Buy Me A Coffee
DigitalOcean Referral Badge
Sign up to get $200, 60-day account credit !