Just tell me how to use Go Modules

- By Dave Wales
Blog post image

I recently started using Go’s new inbuilt vendoring tool, Go Modules, and having come from both govendor and dep, this new tool was more of a change than I expected.

I’m a fan of quick guides – just tell me what to do so I can start using it now. I don’t need an essay on why I should be using it or painful detail on the tool’s inner workings.

Unfortunately, a quick guide like this doesn’t seem to exist, so I’m writing one here.

You’re welcome.

Put your code somewhere other than the gopath

You can technically use Go Modules inside the gopath, but you’ll have to manually set GO111MODULES=on in your environment variables.

That being said, the whole point of modules is to not have to put your code in the gopath, so don’t do that.

Initialise Go Modules

Run this command in your go project:

go mod init <modulename>

modulename is whatever you want to call your module. This name should be fairly unique, because if you have module name clashes you’re gonna have a bad time.

This creates a go.mod file, which you don’t need to touch. Use go get to add the dependencies to the go.mod file.

Just run this:

go get -u ./...

This will add all of your project’s current dependencies to the go.mod file and create a go.sum file. You don’t need to touch that file either.

Vendor those dependencies

Run this:

go mod vendor

This will create a vendor folder and add copies of each dependency listed in your go.mod file to that folder. This folder also can’t be edited, so again, there’s no need to touch it.

Update a dependency

Just run:

go get -u <repo url>

go mod vendor

This will update the dependency version in the go.mod file, and then update the code in your vendor folder for that dependency.

This should be enough for you to get up and running with Go Modules on your go project.

About Dave Wales

Senior Backend Engineer at Kablamo

Tags