Go modules, introduced in Go 1.11, provide a way to manage dependencies and versioning for Go projects. The go mod command is central to this system, allowing you to initialize, update, and manage modules. This guide covers the essential go mod commands with examples.
Initializing a Module
To start using Go modules in your project, create a go.mod file at the root of your project. This file tracks your module’s dependencies.
go mod init [module-path]
For example, to initialize a module named github.com/example/myproject:
go mod init github.com/example/myproject
This creates a go.mod file with the module name and Go version.
Updating Dependencies
After adding imports or changing dependencies, update the go.mod and go.sum files. The go.sum file contains checksums for dependency verification.
go get ./...
This command downloads and installs all dependencies listed in your code, updating the module files accordingly.
Tidying the Module File
After manually editing dependencies (e.g., changing versions), clean up the go.mod file to remove unused dependencies and ensure consistency.
For example, if you change the version of logrus from v1.4.2 to v1.3.2 in go.mod:
github.com/sirupsen/logrus v1.4.2
to
github.com/sirupsen/logrus v1.3.2
Run:
go mod tidy
This updates the file, removes unused modules, and ensures all dependencies are properly listed.
Understanding Dependency Usage
To see why a specific module is included in your dependencies:
go mod why -m [module-path]
Example:
$ go mod why -m github.com/stretchr/testify
# github.com/stretchr/testify
github.com/netqyq/mod-test
github.com/sirupsen/logrus
github.com/sirupsen/logrus.test
github.com/stretchr/testify/assert
This shows the dependency chain leading to the module.
Creating a Vendor Directory
To save all dependencies locally in a vendor directory (useful for reproducible builds or offline development):
go mod vendor
This copies all dependencies into the vendor directory.
Additional Useful Commands
- Download Dependencies:
go mod download- Downloads modules to the local cache without updatinggo.mod. - Edit Module File:
go mod edit- Manually edit thego.modfile (e.g., add or remove requirements). - Verify Checksums:
go mod verify- Verifies that downloaded modules match their checksums ingo.sum. - List Dependencies:
go list -m all- Lists all modules in the current module’s dependency tree.
Best Practices
- Always run
go mod tidyafter changing dependencies. - Use semantic versioning for dependencies.
- Commit
go.modandgo.sumto version control, but consider excludingvendorif using CI/CD. - For private modules, set
GOPRIVATEenvironment variable.