Skip to content
Tutorials Center
My learning

Topics

Lesson 95 of 147 ยท Modules and Packages

Go Modules

Understand Go modules - go.mod and go.sum, go mod tidy and get, semantic import versioning, replace and toolchain, GOPROXY and version selection.

A package is a directory of code; a module is a collection of packages that are released, versioned and downloaded together. A module is identified by a module path (usually the place where its code lives, such as github.com/you/shop) and described by a file named go.mod at its root. Every Go project you build outside a single-file experiment is a module, and every third-party library you use is one too.

Modules answer questions that every ecosystem has to answer: which version of each dependency does my program use, how do I get exactly the same build tomorrow, and how do I know a downloaded dependency was not tampered with? This lesson explains go.mod and go.sum, the commands that maintain them, how versions work (including the unusual rule for major versions), how to redirect or exclude a dependency, how the module proxy and checksum database fit in, and how Go chooses versions with minimal version selection.

The lesson mostly shows files and terminal sessions, which cannot run in the browser editors on this site, so those blocks are read-only and show what you would see on your own machine. The runnable programs implement the same ideas (version comparison, go.mod parsing, version selection, import-path rules and go.sum hashes) so you can see how they work.

Creating a module

Inside an empty directory, go mod init creates go.mod:

Terminal
mkdir shop && cd shop
go mod init example.com/shop
GO.MOD
module example.com/shop

go 1.24.0

The argument is the module path, which becomes the prefix of every import path in the module. A package in shop/internal/orders is imported as example.com/shop/internal/orders. If you plan to publish the module, use the repository URL (github.com/you/shop); for a private or throwaway project, any name works, but it should be unique and dotted so it can never collide with the standard library. Standard packages have no dot in their first path element, which is how the go tool tells them apart.

The go line says which Go language version the module's code needs. Since Go 1.21 it is a real minimum: a Go toolchain older than the line refuses to build the module, and it also selects language features (for example, per-iteration loop variables apply only in modules that declare go 1.22 or newer).

Anatomy of go.mod

Here is a go.mod with every common directive:

GO.MOD
// Module for the shop API
module example.com/shop

go 1.24.0

toolchain go1.24.3

require (
	github.com/go-chi/chi/v5 v5.2.1
	github.com/jackc/pgx/v5 v5.7.4
	golang.org/x/text v0.23.0 // indirect
)

require github.com/google/uuid v1.6.0

replace github.com/jackc/pgx/v5 => ../pgx-fork

exclude golang.org/x/text v0.20.0

retract v1.0.1 // published by mistake

The directives are:

Directive Meaning
module The module path. Exactly one per file.
go Minimum Go language version for this module.
toolchain The suggested toolchain version to use (see below). Optional.
require A dependency and the minimum version this module needs.
replace Substitute one module (or one version) with another module or a local directory.
exclude Forbid a specific version of a dependency from being selected.
retract Mark versions of this module as bad, so users get a warning.
tool Declare a tool dependency you run with go tool (Go 1.24).

A // indirect comment marks a requirement your own code does not import directly; it is needed by one of your dependencies, and recorded so that the build is reproducible. go mod tidy maintains these comments for you. Go 1.17 and later list all indirect dependencies in go.mod, which is why the file is often longer than you expect.

You normally edit go.mod with commands (go get, go mod tidy, go mod edit) rather than by hand, but it is a plain text file and hand edits are allowed.

This small program shows how little structure there is. It reads the file above line by line, handling comments and require ( ... ) blocks:

Go Reading a go.mod file

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with bufio.Scanner or fmt.Scan), it gets the next line from this box.

In real code, parse go.mod with the official golang.org/x/mod/modfile package, which understands every directive and can write the file back. The point of this toy is the shape of the format: directive, then arguments, with optional ( ... ) grouping.

Versions

Go modules use semantic versioning: vMAJOR.MINOR.PATCH, always with a leading v, optionally followed by a pre-release (v1.2.0-rc.1). A patch release fixes bugs, a minor release adds features compatibly and a major release may break compatibility. Releases are created by tagging the repository (git tag v1.4.2); there is no registry to upload to.

The go/version package (Go 1.22) compares Go toolchain versions, which have their own format (go1.22.3, go1.22rc1). It is a nice way to see the ordering rules in action:

Go Comparing Go versions with go/version

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with bufio.Scanner or fmt.Scan), it gets the next line from this box.

Compare returns -1, 0 or +1, so it plugs straight into slices.SortFunc. Two details matter: comparison is numeric (go1.9 is less than go1.10, unlike a plain string comparison), and go1.21 (the language version) sorts before go1.21.0 (the first release), while a release candidate like go1.22rc1 sorts before the final go1.22. Lang strips everything after the language version, giving go1.22 for all of the 1.22.x releases and release candidates.

Pseudo-versions

You can depend on a commit that was never tagged, for example the latest commit of a branch. Go then records a pseudo-version that encodes the base version, the commit time and a commit hash:

TEXT
v0.0.0-20250102150405-abcdef123456

Pseudo-versions sort correctly relative to real releases, so tools can still tell which of two is newer. Treat them as a sign that a dependency has no release you can pin to.

Major versions are part of the import path

Here Go does something unusual, called semantic import versioning: version 2 and above of a module have the major version at the end of the module path, and therefore in every import path.

Go
import (
	"github.com/go-chi/chi/v5"   // module github.com/go-chi/chi/v5
	"github.com/google/uuid"     // v1: no suffix
)
GO.MOD
module github.com/go-chi/chi/v5

The rule gives a strong guarantee: an import path always names a compatible API. A program can even import example.com/lib (v1) and example.com/lib/v2 side by side, because they are different packages as far as Go is concerned. Moving to a new major version is therefore explicit: you change the import paths, and the compiler finds every call that needs attention. Versions v0 and v1 carry no suffix. As a module author, you release v2 by changing the module line to end in /v2 (and your code's own imports to match), then tag v2.0.0.

This program implements the path rules, including how the module proxy escapes capital letters:

Go Major version suffixes and proxy escaping

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with bufio.Scanner or fmt.Scan), it gets the next line from this box.

example.com/v1 is not a v1 suffix (v1 never appears in a path), and example.com/vendor merely starts with the letter v. Our toy also leaves gopkg.in/yaml.v3 at major 1, because that service uses its own .vN convention; the real parser (module.SplitPathVersion in golang.org/x/mod) knows about it. The second half shows why paths on the proxy contain ! characters: the proxy and the module cache escape each capital letter as ! plus its lowercase form, so that they work on case-insensitive file systems such as Windows and macOS.

Everyday commands

Terminal
go mod init example.com/shop     # create go.mod
go get github.com/go-chi/chi/v5  # add a dependency (latest version)
go get github.com/go-chi/chi/v5@v5.1.0   # a specific version
go get github.com/go-chi/chi/v5@latest   # explicitly the newest release
go get -u ./...                  # upgrade dependencies of the packages in this module
go mod tidy                      # add missing, remove unused requirements
go mod download                  # fill the module cache without building
go mod verify                    # check cached modules still match go.sum
go mod vendor                    # copy dependencies into ./vendor
go mod why golang.org/x/text     # why is this module needed?
go mod graph                     # print the requirement graph
go list -m all                   # the final list of all modules in the build
go list -m -u all                # same, plus available upgrades
go mod edit -replace=old=new     # script edits to go.mod

The two you will use all the time are go get (to change which version you require) and go mod tidy. tidy scans every package in your module, including test files, and makes go.mod match exactly: it adds requirements for imports you added, removes the ones you no longer need and updates go.sum. Run it before committing. A typical session looks like this:

TEXT
$ go get github.com/google/uuid
go: added github.com/google/uuid v1.6.0

$ go mod why github.com/google/uuid
# github.com/google/uuid
example.com/shop/internal/orders
github.com/google/uuid

$ go list -m all
example.com/shop
github.com/go-chi/chi/v5 v5.2.1
github.com/google/uuid v1.6.0
...

(go mod why prints the shortest chain of imports that makes the build depend on the package. Handy when a surprising library shows up.)

The first time a module is needed, Go downloads it into the module cache ($GOPATH/pkg/mod, shared by all your projects and read-only). Builds then use the cache. go clean -modcache empties it.

go.sum: integrity, not versions

Next to go.mod you will find go.sum, which lists a cryptographic hash for each module version the build uses:

TEXT
github.com/google/uuid v1.6.0 h1:NIvaJDMOsjHA8n1jAhLSgzrAzy1Hgr+hNrb57e+94F0=
github.com/google/uuid v1.6.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo=

(The two hashes above only illustrate the format.) Each module has two lines: one for the module's whole file tree, one for just its go.mod file. Go checks the hash every time it unpacks a module, so if a dependency's code is changed behind the same version number, the build fails with a "checksum mismatch" instead of silently running different code. You commit go.sum to version control and never edit it by hand.

The h1: hash is simple: it is the SHA-256 of a text listing that contains the SHA-256 of each file and its name, sorted by name, encoded in Base64. The program below implements that scheme for a pretend module held in memory:

Go How an h1 hash is built

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with bufio.Scanner or fmt.Scan), it gets the next line from this box.

Change a single character in one file, here + to -, and the whole hash changes. That is all the tamper protection needs: the first time you add a module, Go also asks the checksum database whether anyone else has ever seen a different hash for the same version.

Choosing versions: minimal version selection

If your program needs module A, which needs C v1.3.0, and module B, which needs C v1.4.0, which C do you get? Many ecosystems solve this with a constraint solver that tries to find the newest versions satisfying all ranges. Go uses a deliberately simple rule called minimal version selection (MVS): every requirement is a minimum, and Go selects the highest version that anyone requires, no higher. Builds therefore never change just because a newer release appeared: a new version of a dependency is used only when somebody asks for it with go get.

Go Minimal version selection by hand

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with bufio.Scanner or fmt.Scan), it gets the next line from this box.

The program walks the requirement graph and remembers the highest version it meets for each module path. The result is C v1.4.0 (the higher of 1.3.0 and 1.4.0) and D v1.2.0 (required by C v1.4.0), even though other paths in the graph asked for D v1.0.0 and v1.1.0. Notice what MVS never does: it never picks a version nobody asked for, and it never needs a lock file to stay stable, because go.mod already records the minimum versions. This is why go.mod plus go.sum give reproducible builds.

(The real implementation prunes the graph, since Go 1.17, so that large dependency trees load quickly, but the selection rule is the one above.)

replace, exclude, retract and toolchain

replace redirects a module to another source. It is the tool for working on a dependency and your program at the same time, for testing a fix before it is released, and for using a fork:

GO.MOD
// use a local checkout
replace github.com/jackc/pgx/v5 => ../pgx-fork

// use a fork at a specific version
replace github.com/old/lib v1.2.3 => github.com/you/lib v1.2.4

replace directives only apply when your module is the main module. If someone imports your library, your replace lines are ignored, so do not rely on them in published libraries. For multi-module workspaces on your own machine, use go.work (covered in Project Layout).

exclude forbids one specific version of a dependency (say, one with a known bug), so MVS moves on to the next higher version that is not excluded. It is rarely needed. retract is for module authors: you publish a new version whose go.mod retracts earlier versions (retract v1.0.1, or a range retract [v1.0.0, v1.0.5]), and tools then warn users that those releases should not be used. Retraction is how you handle a release you published by mistake, since a version, once the proxy has served it, can never be deleted or replaced.

toolchain and the go line work together. Since Go 1.21 the go command can download and run a newer toolchain when a module requires one: if go.mod says go 1.24.0 and you have Go 1.22 installed, the command fetches Go 1.24 and uses it. The GOTOOLCHAIN environment variable controls this (local disables switching, auto is the default). The toolchain line is the preferred version when it differs from the minimum.

The module proxy and checksum database

By default Go does not fetch modules straight from GitHub. It asks a module proxy, a caching HTTP service, which makes downloads fast and keeps them available even if the original repository is deleted. Three environment variables control the system:

Terminal
go env GOPROXY    # https://proxy.golang.org,direct
go env GOSUMDB    # sum.golang.org
go env GOPRIVATE  # (empty)
  • GOPROXY is a comma-separated list. direct means "fall back to the version control system". Companies often run their own proxy (GOPROXY=https://goproxy.example.com,direct). GOPROXY=off forbids all downloads, which is how this site's sandbox is configured.
  • GOSUMDB names the transparency log that stores a hash for every public module version, as described above. It protects you from a malicious proxy or from a changed tag.
  • GOPRIVATE lists module path patterns (GOPRIVATE=git.example.com/*,github.com/mycompany/*) that are private: they skip the public proxy and the checksum database, so the names of your private repositories never leave your network. GONOPROXY and GONOSUMDB fine-tune each half.
Terminal
GOFLAGS=-mod=vendor go build ./...   # build from ./vendor, offline
go env -w GOPRIVATE=github.com/mycompany/*   # saved in the user's go env file

Vendoring (go mod vendor) copies all dependencies into a vendor/ directory inside your repository. Builds then work offline and don't need the module cache. When vendor/ exists and the go line is 1.14 or newer, the go command uses it by default. Most projects don't vendor, since the proxy and go.sum already provide reproducibility, but it remains useful for air-gapped builds and for auditing every line you ship.

Never commit credentials into go.mod, a replace path or a GOPROXY URL. For private repositories, use a .netrc file, a credential helper or an SSH-based git configuration, and set GOPRIVATE so the tooling does not leak names to public services.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. The dependencies of a program need lib v1.3.0 (from module A) and lib v1.5.0 (from module B), and lib v1.9.0 has just been released. Which version does Go select?

    Minimal version selection picks the highest version that anything in the build requires, v1.5.0 here. It does not jump to v1.9.0 unless you run go get for it.
  2. 2. A module whose path ends in /v3 is imported as example.com/lib/v3. What is the reason for the suffix?

    For v2 and above the major version is part of the module path and every import path. This guarantees an import path always names a compatible API.
  3. 3. What does go mod tidy do?

    tidy makes go.mod match the imports in your packages and tests. It does not upgrade versions; that is go get -u.
  4. 4. What is go.sum for?

    go.mod already holds the required versions. go.sum stores hashes so that Go can verify a downloaded module is exactly what everyone else got.
  5. 5. Your go.mod contains a replace directive. Does it affect programs that import your published module?

    Replace (and exclude) directives are honored only in the main module's go.mod. Dependencies' replace lines are ignored.

Summary

  • A module is a versioned collection of packages described by go.mod; its module path prefixes all import paths inside it.
  • go.mod holds module, go, toolchain, require, replace, exclude, retract and tool directives; // indirect marks requirements your own code doesn't import.
  • Versions are semantic (v1.4.2) and come from repository tags; untagged commits get pseudo-versions. From v2 on, the major version is part of the module and import path.
  • go get changes versions, go mod tidy synchronizes go.mod and go.sum with the code, and go mod why, go list -m all and go mod graph explain the dependency picture.
  • go.sum records content hashes (SHA-256, h1:) and is checked against the public checksum database; commit it and don't edit it.
  • Minimal version selection uses the highest required version of each module, so builds are reproducible without a lock file and don't drift when new releases appear.
  • GOPROXY, GOSUMDB and GOPRIVATE control where modules come from and which are private; vendoring copies dependencies into your repository.

Next: Project Layout and Multi-File Programs