The toolchain directive in go.mod was introduced in Go 1.21. An older toolchain cannot parse it and rejects go.mod entirely, so the build fails before compiling.
What this error means
A build fails with go.mod:4: unknown directive: toolchain. The workflow runs a pre-1.21 Go that does not understand the toolchain line.
Go module errors name the module but rarely the layer that failed. Separate the three: the module path does not resolve, the proxy cannot serve it, or the checksum database disagrees with what was downloaded.
Terminal
# what Go resolves and from where
go env GOPROXY GOSUMDB GOPRIVATE GOFLAGS
# does the module resolve at all, bypassing the build?
go list -m -versions github.com/org/module
# verify the module cache against go.sum
go mod verify
# private modules must be excluded from proxy and sumdb
go env -w GOPRIVATE=github.com/yourorg/*
Common causes
CI Go older than 1.21
The runner installed a pre-1.21 Go, which cannot parse the toolchain directive.
toolchain line added by a newer local Go
A newer local Go wrote a toolchain directive that the older CI toolchain rejects.
How to fix it
Upgrade the CI Go
Install Go 1.21 or newer so the toolchain directive parses.
.github/workflows/ci.yml
- uses:actions/setup-go@v5with:go-version:'1.22'
Track the version from go.mod
Drive setup-go from go.mod so CI never lags the directive.
Keep the CI Go at or above the version go.mod requires.
Use go-version-file: go.mod to avoid drift.
Bump CI when a newer local Go writes a toolchain line.
Frequently asked questions
What causes Go "unknown directive: toolchain"?
There are 2 common causes: ci go older than 1.21 and toolchain line added by a newer local go. The runner installed a pre-1.21 Go, which cannot parse the toolchain directive.
How do I fix Go "unknown directive: toolchain"?
There are 2 fixes depending on which cause you have: upgrade the ci go and track the version from go.mod. Work through them in order, since the first is the most common.
What does Go "unknown directive: toolchain" actually mean?
A build fails with go.mod:4: unknown directive: toolchain.
How do I stop Go "unknown directive: toolchain" happening again?
Keep the CI Go at or above the version go.mod requires. The prevention section lists 3 changes that keep it from recurring.