LinuxCommandLibrary

go-mod

Manage Go modules and dependencies

TLDR

Initialize new module in current directory

$ go mod init [moduleName]
copy

Download modules to local cache
$ go mod download
copy

Add missing and remove unused modules
$ go mod tidy
copy

Verify dependencies have expected content
$ go mod verify
copy

Copy sources of all dependencies into the vendor directory
$ go mod vendor
copy

SYNOPSIS

go mod [arguments]

PARAMETERS

download
    Download modules to the local module cache.

edit
    Edit go.mod from command line or editor.

graph
    Print module requirement graph.

init
    Initialize new module in current directory.

tidy
    Add missing and remove unused modules.

vendor
    Make copy of modules to the vendor directory.

verify
    Verify dependencies have expected content.

why
    Explain why packages or modules are needed.

DESCRIPTION

The `go mod` command is a suite of tools for managing Go modules, which are collections of related Go packages that are versioned together. It is used to create, modify, and manage the `go.mod` file, which declares the module's dependencies. The `go mod` command also handles downloading and verifying dependencies. Modules enable reproducible builds and simplified dependency management. It replaced `GOPATH` for dependency resolution.

CAVEATS

Requires a valid Go installation and a `go.mod` file in the working directory or a parent directory for many subcommands.

USING GO.MOD DIRECTLY

While `go mod edit` allows for automated `go.mod` file changes, manual editing is also possible. Exercise caution when manually modifying the file, ensuring correct syntax and version specifications to avoid build errors. Common errors include syntax mistakes, typo's or invalid module definitions.

Example of a go.mod file:
module example.com/myproject

go 1.18

require (
golang.org/x/text v0.3.0
golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2 // indirect
)

VENDORING

The go mod vendor command creates a vendor directory containing copies of all dependencies used by the module. This approach isolates the project from external changes in dependencies and ensures repeatable builds, especially for deployment or archival purposes. Vendoring is not the default, however, is widely used.

MODULE CACHING

Go modules are downloaded and cached in a local module cache, typically located at $GOPATH/pkg/mod or $HOME/go/pkg/mod (if GOPATH is not set). This cache avoids redundant downloads of the same module version across different projects.

HISTORY

Go modules were introduced in Go 1.11 as an experimental feature and became the default in Go 1.16. They replaced the `GOPATH`-based dependency management system, offering more reliable and reproducible builds. The development of `go mod` was driven by the need for a standardized and versioned dependency management solution within the Go ecosystem.

SEE ALSO

go(1)

Copied to clipboard