Skip to content
Latchkey

Go "cannot find main module" / "go.mod not found" - Fix in CI

A go command ran in a directory with no go.mod in it or any parent. Without a module root, Go has no main module to operate on and refuses before doing anything.

What this error means

A command fails immediately with go: cannot find main module or go.mod file not found in current directory or any parent directory. It usually means CI ran the build from the wrong working directory or before checkout placed go.mod.

go output
go: go.mod file not found in current directory or any parent directory;
	see 'go help modules'

Common causes

Build run from the wrong directory

CI executed go build from a path above the module root, or from a subdirectory that is not under the module, so no go.mod is in scope.

go.mod missing from the repository

The project was never initialized as a module (no go mod init), so there is no go.mod to find anywhere up the tree.

A monorepo with the module in a subfolder

The go.mod lives in a subdirectory, but the job ran from the repo root where there is no module file.

How to fix it

Run from the module root

Change into the directory that contains go.mod before running any go command.

.github/workflows/ci.yml
cd "$GITHUB_WORKSPACE/service"   # where go.mod lives
go build ./...

Initialize the module if it is missing

Terminal
go mod init github.com/yourorg/yourrepo
go mod tidy

Point the action at the subdirectory

For monorepos, set the working directory so each go command resolves the right module.

.github/workflows/ci.yml
- run: go build ./...
  working-directory: service

How to prevent it

  • Always run go commands from the directory containing go.mod.
  • Set working-directory for modules nested in a monorepo.
  • Commit a go.mod at the module root.

Related guides

Tired of flaky CI? Latchkey auto-heals failed jobs and retries them for you. Start free →