Skip to main content

Programming languages · Intermediate · 22 min

Manage dependencies and versions with Go modules

By Padding · Updated 18 Nov 2026
Go 1.27.4 · Linux (golang:1.27 image)

You will build a small Go 1.27 program with a pinned third-party package, read every line of its go.mod and go.sum, see how minimal version selection picks versions, add govulncheck as a tool dependency to find and fix a real vulnerability, and work on a second module locally with replace and then go work.

On this page

A Go module is a folder with a go.mod file at its root. That file names the module, says which Go version it needs and lists the exact versions of the other modules it uses. Next to it, go.sum holds a checksum for every module version that has been downloaded, so a changed or tampered copy is refused. There is no separate lock file and no install step: the go command reads these two files and fetches what it needs from the module proxy.

This tutorial builds greet, a small program that picks a greeting from a browser-style language list such as ha-NG,fr;q=0.8. It uses golang.org/x/text, maintained by the Go team. You pin an old version on purpose, read both files line by line, watch how Go chooses versions, add govulncheck as a tool the module tracks, let it find a real vulnerability in that old version and fix it. Then you move the greetings into a second module and work on both at once, first with a replace directive and then with a workspace.

Everything lives in ~/go-modules-demo, which you delete at the end.

Step 1 · Create the module and pin a dependency

Create the folder and the module. The module path example.com/greet looks like an import path, but it only has to be a real address if other people will download the module:

Bash
mkdir -p ~/go-modules-demo/greet
cd ~/go-modules-demo/greet
go mod init example.com/greet

Create main.go. It parses the language list, asks a matcher which supported language fits best and prints the greeting at the same position:

Bash
cat > main.go <<'GO'
package main

import (
	"fmt"
	"os"

	"golang.org/x/text/language"
)

var supported = []language.Tag{
	language.English,
	language.French,
	language.Swahili,
	language.MustParse("ha"),
	language.Portuguese,
}

var hello = []string{"Hello", "Bonjour", "Habari", "Sannu", "Olá"}

var matcher = language.NewMatcher(supported)

func main() {
	accept := "en"
	if len(os.Args) > 1 {
		accept = os.Args[1]
	}
	wanted, _, err := language.ParseAcceptLanguage(accept)
	if err != nil {
		fmt.Fprintln(os.Stderr, "bad language list:", err)
		os.Exit(1)
	}
	_, i, _ := matcher.Match(wanted...)
	fmt.Println(hello[i])
}
GO

language.MustParse("ha") builds the tag for Hausa, which has no named constant in the package. The matcher returns the index of the best supported tag, or index 0 (English) when nothing fits.

Now add the dependency at one exact version. @v0.3.7 is a release from 2021, chosen deliberately so a later step has something to find. Then run go mod tidy, which reads your imports and corrects go.mod to match them:

Bash
go get golang.org/x/text@v0.3.7
go mod tidy
go run . 'ha-NG,fr;q=0.8'
go run . pt-MZ
go run . de

The language list works like a browser's Accept-Language header: Hausa as spoken in Nigeria first, then French with a lower weight (q=0.8).

Check it worked

go get prints go: downloading golang.org/x/text v0.3.7 and go: added golang.org/x/text v0.3.7. The three runs print Sannu, Olá and Hello. Portuguese as written in Mozambique (pt-MZ) matches plain Portuguese, and German (de) is not supported, so the program falls back to English.

Step 2 · Read go.mod and go.sum

Print both files:

Bash
cat go.mod
cat go.sum

go.mod has three parts:

Text
module example.com/greet

go 1.27.4

require golang.org/x/text v0.3.7
  • module is the module's path. Imports of packages inside this module start with it.
  • go is the minimum Go version the module needs, and it also sets the language features the compiler allows in this module. go mod init writes the full version of the Go you ran it with, here 1.27.4.
  • require lists each module this one depends on and the minimum version it needs. A module you use only through another module gets an // indirect comment. go get can leave that comment on a direct dependency too; go mod tidy removes it once it sees the import.

go.sum has exactly two lines, both for x/text:

Text
golang.org/x/text v0.3.7 h1:olpwvP2KacW1ZWvsR7uQhoyTYvKAupfQrRGBFM352Gk=
golang.org/x/text v0.3.7/go.mod h1:u+2+/6zg+i71rQMx5EYifcz6MCKuco9NR6JIITiCfzQ=

x/tools, which x/text requires (you meet it in the next step), gets no line here: nothing in this build needs its code or its go.mod. The first line is a hash of every file in that module version. The second is a hash of its go.mod alone. Go sometimes needs only a module's go.mod, to learn what it requires, without downloading its code, so that line can exist on its own. h1: names the hash scheme, a SHA-256 over the file tree. On the first download, Go also checks these hashes against the public checksum database at sum.golang.org, so everyone who fetches v0.3.7 gets identical bytes. Commit both files.

Ask Go to check the copies in your module cache against go.sum:

Bash
go mod verify

On prepaid data or a slow connection, it helps to know that each version is downloaded once into the module cache (go env GOMODCACHE prints where) and reused by every project on the machine. With GOPROXY=off set for a command, Go refuses to download anything and builds only from the cache, which is a quick way to see whether you can work offline.

Check it worked

The two files match the listings above: go.mod says go 1.27.4 and go.sum has two lines. go mod verify prints all modules verified.

Step 3 · See why Go does not pick the latest version

List every module in the build graph with the version Go selected, then the requirement edges behind those choices:

Bash
go list -m all
go mod graph

go list -m all shows three modules: your own, golang.org/x/text v0.3.7 and golang.org/x/tools at a 2018 pseudo-version, v0.0.0-20180917221912-90fa682c2a6e. A pseudo-version stands for a commit that had no release tag: the date and time of the commit, then its hash. Nothing in your code mentions x/tools. It is there because the go.mod of x/text v0.3.7 requires it, and go mod graph prints that edge as golang.org/x/text@v0.3.7 golang.org/x/tools@v0.0.0-....

x/tools has had dozens of releases since 2018, and Go still chose the old commit. This is minimal version selection (MVS). Each require line is a minimum, and for each module Go selects the highest of the minimums that appear anywhere in the graph, never anything newer. If your module asked for v1.2.0 of some package and another dependency asked for v1.4.0, Go would build with v1.4.0, even if v1.9.0 existed. The result depends only on the go.mod files, not on the day you run the build, so the same commit builds with the same versions on every machine without a lock file. A new release of a dependency changes nothing until someone raises a requirement.

To see what you could move to, add -u:

Bash
go list -m -u all

Check it worked

The go list -m -u all output shows something like golang.org/x/text v0.3.7 [v0.44.0]. The version in brackets is the newest available release, which is v0.44.0 at the time of writing. It is information only: go.mod still says v0.3.7 until you run go get with a new version.

Step 4 · Keep go.mod honest with go mod tidy

Dependencies tend to pile up when someone adds a package, tries it and deletes the code. Reproduce that by adding a module nothing imports:

Bash
go get github.com/google/uuid@v1.6.0
cat go.mod

go.mod now has a second require block with github.com/google/uuid v1.6.0 // indirect. Go cannot tell from go get alone whether you intend to use it. Run tidy and look again:

Bash
go mod tidy
grep uuid go.mod go.sum || echo "no uuid lines left"

go mod tidy walks every package and test in the module, adds any requirement an import needs, and removes requirements and go.sum lines that nothing uses. Run it before each commit that changes imports. A CI job can run go mod tidy -diff, which prints the changes tidy would make, and fail when the output is not empty.

Check it worked

The grep finds nothing, so the command prints no uuid lines left. go.mod is back to the single require golang.org/x/text v0.3.7 line.

Step 5 · Set the go and toolchain lines

The go line is a requirement for everyone who builds the module. 1.27.4 asks for the latest patch release, which is stricter than the code needs. Lower it to the first release of 1.27, and record the release you actually work with in a toolchain line:

Bash
go mod edit -go=1.27.0 -toolchain=go1.27.4
cat go.mod
go version

The two lines do different jobs:

  • go 1.27.0 is the minimum. Someone with Go 1.26 who builds this module does not get a compile error part-way through. With the default GOTOOLCHAIN=auto setting, their go command downloads a Go 1.27 toolchain from the module proxy and uses that instead.
  • toolchain go1.27.4 is a preference. When the local Go is older than it, the go command switches to go1.27.4 for work in this module. When the local Go is newer, the line is ignored. It never stops anyone from building.

Use go mod edit for changes like this, rather than editing go.mod by hand, because it rewrites the file in Go's own format.

Check it worked

go.mod now reads go 1.27.0, then a blank line, then toolchain go1.27.4, then the require line. go version prints go version go1.27.4 followed by your operating system and architecture, for example linux/amd64.

Step 6 · Track govulncheck as a tool and fix what it finds

govulncheck compares your code with the Go vulnerability database. Since Go 1.24, a module can record the tools its developers run with a tool directive, so everyone uses the same version without a separate install. First note the x/tools version selected now, then add the tool:

Bash
go list -m golang.org/x/tools
go get -tool golang.org/x/vuln/cmd/govulncheck@v1.10.0
go list -m golang.org/x/text golang.org/x/tools
cat go.mod

go.mod gains a line tool golang.org/x/vuln/cmd/govulncheck and a block of // indirect requirements for the modules the tool is built from. Look at x/tools: it moved from the 2018 pseudo-version to v0.53.0. The govulncheck module requires x/tools v0.53.0, and MVS takes the highest minimum in the graph. Tools share one graph with your code, so adding a tool can raise versions your program builds with. The tool's code is not compiled into your binary.

Run the tool through go tool:

Bash
go tool govulncheck ./...

It reports one vulnerability, GO-2022-1059: a crafted Accept-Language value can make language.ParseAcceptLanguage take a very long time, which is a denial of service for a server that parses headers from strangers. The report gives Found in: golang.org/x/text@v0.3.7, Fixed in: golang.org/x/text@v0.3.8 and a trace such as main.go:27:48: greet.main calls language.ParseAcceptLanguage. govulncheck checks which functions your code actually calls, so it lists other known issues in your dependencies separately, as ones your code does not reach. It exits with status 3 when your code is affected, which fails a CI job without extra scripting.

Upgrade x/text. v0.3.8 is the smallest fix; this module moves to the newest release so the next upgrade is not years of changes at once. Then tidy and scan again:

Bash
go get golang.org/x/text@v0.44.0
go mod tidy
go tool govulncheck ./...
go run . 'ha-NG,fr;q=0.8'

go get prints go: upgraded golang.org/x/text v0.3.7 => v0.44.0. The newer x/text needs Go 1.26 or later, which the go 1.27.0 line already covers. If a dependency ever needs a newer Go than your go line, go get raises the line and tells you.

Check it worked

The second scan prints No vulnerabilities found. and exits with status 0. go run still prints Sannu, so the upgrade changed nothing you depend on. go.mod now requires golang.org/x/text v0.44.0.

Step 7 · Work on a dependency locally with replace

Suppose the greetings belong in a separate module, example.com/phrases, that several programs share, and you are adding Amharic to it. You want to try the change in greet before tagging a release. A replace directive points a module path at a folder on disk.

Create the second module next to the first:

Bash
mkdir -p ~/go-modules-demo/phrases
cd ~/go-modules-demo/phrases
go mod init example.com/phrases
go mod edit -go=1.27.0
cat > phrases.go <<'GO'
// Package phrases holds greetings keyed by base language code.
package phrases

// Hello returns a greeting for a base language code such as "sw",
// or the English greeting for a code it does not know.
func Hello(lang string) string {
	switch lang {
	case "fr":
		return "Bonjour"
	case "sw":
		return "Habari"
	case "ha":
		return "Sannu"
	case "pt":
		return "Olá"
	case "am":
		return "ሰላም"
	}
	return "Hello"
}
GO

Go source is UTF-8, so the Amharic greeting in Ge'ez script needs no special handling. Replace greet's main.go so it asks phrases for the text. It now takes the language part of the matched tag, such as am from am-ET:

Bash
cd ~/go-modules-demo/greet
cat > main.go <<'GO'
package main

import (
	"fmt"
	"os"

	"example.com/phrases"
	"golang.org/x/text/language"
)

var matcher = language.NewMatcher([]language.Tag{
	language.English,
	language.French,
	language.Swahili,
	language.MustParse("ha"),
	language.Portuguese,
	language.Amharic,
})

func main() {
	accept := "en"
	if len(os.Args) > 1 {
		accept = os.Args[1]
	}
	wanted, _, err := language.ParseAcceptLanguage(accept)
	if err != nil {
		fmt.Fprintln(os.Stderr, "bad language list:", err)
		os.Exit(1)
	}
	tag, _, _ := matcher.Match(wanted...)
	base, _ := tag.Base()
	fmt.Println(phrases.Hello(base.String()))
}
GO

Add a requirement for phrases and the replacement in one edit, tidy, and run:

Bash
go mod edit -require=example.com/phrases@v1.0.0 -replace=example.com/phrases=../phrases
go mod tidy
tail -n 3 go.mod
go run . am-ET
go run . 'ha-NG,fr;q=0.8'

A require line always needs a version, so v1.0.0 stands in for the release you would normally depend on. With the replace line in place, Go reads the code from ../phrases and never tries to download that version, and no go.sum line is needed for a local folder. A replace only takes effect in the module where it is written; programs that depend on greet ignore it.

Check it worked

The end of go.mod reads replace example.com/phrases => ../phrases. The runs print ሰላም and Sannu. If your terminal shows boxes instead of the Amharic word, the output is right and the terminal font lacks Ge'ez glyphs.

Step 8 · Swap replace for a workspace

The replace approach has a cost: the directive sits in greet's go.mod, holds a path that only exists on your machine, and is easy to commit by accident. A workspace keeps that information in a separate go.work file instead. Remove both the replacement and the stand-in requirement, then create a workspace one level up that uses both modules:

Bash
go mod edit -dropreplace=example.com/phrases -droprequire=example.com/phrases
cd ~/go-modules-demo
go work init ./greet ./phrases
cat go.work
go run ./greet am-ET

go.work holds a go line and a use block listing ./greet and ./phrases. Every module listed there is a main module, so an import of example.com/phrases resolves to the folder without any line in greet's go.mod. The go command finds go.work by looking in the current folder and its parents, so commands run inside greet use it too:

Bash
cd ~/go-modules-demo/greet
go env GOWORK
go run . sw

Keep go.work out of version control for a setup like this: it describes folders on your machine. Once phrases has a tagged release in its repository, you would run go get example.com/phrases@ followed by that version in greet, delete go.work, and greet would build anywhere. Until then, setting GOWORK=off for a command shows you what a fresh checkout of greet sees: an error that no required module provides example.com/phrases.

Check it worked

go env GOWORK prints the full path of go-modules-demo/go.work in your home folder. go run . sw prints Habari, and greet/go.mod contains no mention of phrases.

Step 9 · Clean up

Delete the demo folder. Go and the module cache stay:

Bash
cd ~
rm -rf ~/go-modules-demo

The downloaded modules remain in the module cache for other projects. To empty the cache completely, which forces every project on the machine to download its dependencies again, run:

Bash
go clean -modcache

Check it worked

ls ~/go-modules-demo reports that there is no such file or directory.

Next steps

Need this done for you?

Padding does this work for growing companies, from the first diagnosis to a system that keeps working.

Platform Engineering

Get new tutorials

New tutorials, about twice a month.