What are modules?
A module is a collection of Go packages stored in a file tree with ago.mod file at its root, provided the directory is outside $GOPATH/src.
Go modules were introduced in Go 1.11, which brings native support for versions and modules. Earlier, we needed the GO111MODULE=on flag to turn on the modules functionality when it was experimental. But now after Go 1.13 modules mode is the default for all development.
What is GOPATH?
GOPATH is a variable that defines the root of your workspace and it contains the following folders:
- src: contains Go source code organized in a hierarchy.
- pkg: contains compiled package code.
- bin: contains compiled binaries and executables.
Modules provide a better way to manage dependencies compared to the old GOPATH-based approach.
Creating a Module
Initialize a new module
Use
go mod init command to create a new module and initialize the go.mod file:A Go module can correspond to a Github repository as well if you plan to publish this module:
Managing Dependencies
Installing Dependencies
To add a new dependency, use thego install command:
go.sum file is also created. This file contains the expected hashes of the content of the modules.
Listing Dependencies
You can list all the dependencies usinggo list command:
Cleaning Up Dependencies
If a dependency is not used, you can remove it usinggo mod tidy command:
The
go mod tidy command adds missing dependencies and removes unused ones automatically.Vendoring
Vendoring is the act of making your own copy of the 3rd party packages your project is using. Those copies are traditionally placed inside each project and then saved in the project repository. This can be done throughgo mod vendor command.
Let’s see an example:
Common Module Commands
| Command | Description |
|---|---|
go mod init | Initialize a new module |
go install | Install a package and add it to go.mod |
go list -m all | List all module dependencies |
go mod tidy | Add missing and remove unused modules |
go mod vendor | Create a vendor directory with dependencies |