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 [-mod=modfile] [command [arguments]]
where command is: download, edit, graph, help, init, tidy, vendor, verify, why

PARAMETERS

-mod=modfile
    Use the specified go.mod file instead of go.mod in the current directory

download [patterns]
    Download modules to local cache

edit
    Edit go.mod from tools or scripts

graph
    Print the module requirement graph

init [module]
    Initialize new module in current directory

tidy
    Add missing modules, remove unused ones; update go.mod and go.sum

vendor
    Generate vendor/ directory with copies of dependencies

verify
    Verify vendor modules against go.sum checksums

why [-m module] [-n] packages
    Explain why specified packages need certain modules

DESCRIPTION

The go mod command is part of the Go toolchain and provides essential functionality for managing Go modules, which are the official way to handle dependencies in modern Go projects.

Go modules, introduced to replace the older GOPATH workspace model, allow developers to declare dependencies in a go.mod file and lock them in a go.sum file for reproducibility. go mod encompasses several subcommands that handle initialization, downloading, cleaning, and verifying modules.

Key operations include creating a new module with go mod init, automatically adding required modules and pruning unused ones with go mod tidy, downloading modules to the local cache via go mod download, and generating a vendor directory for offline builds using go mod vendor. It ensures reproducible builds by verifying checksums and supports dependency analysis with commands like go mod graph and go mod why.

This command is crucial for Go 1.11+ projects, promoting hermetic builds and simplifying dependency management across teams and environments. It integrates seamlessly with other go commands like go build and go test.

CAVEATS

Requires Go 1.11 or later; GOPATH mode deprecated in Go 1.17+. Proxy settings via GOPROXY affect downloads. Not for vendoring in production without verification.

COMMON WORKFLOW

go mod init example.com/myproject
go mod tidy
go mod vendor (for vendoring)

ENVIRONMENT VARIABLES

GOPROXY: module proxy URL (default: proxy.golang.org).
GOSUMDB: checksum database (default: sum.golang.org).
GO111MODULE: legacy control (off/auto/on).

HISTORY

Introduced in Go 1.11 (2018) as experimental support for modules; stabilized in Go 1.13 (2019); became default dependency management in Go 1.16 (2021), with GOPATH mode deprecated.

SEE ALSO

go(1), go-build(1), go-get(1), go-list(1)

Copied to clipboard