The error occurs because your current directory is not the root of a Go module, meaning go.mod is missing or you are running commands in a subdirectory. Initialize a new module with go mod init if one doesn't exist, or navigate to the project root where the file is located.
If you are starting a new project, run the following command in your project's root folder to generate the go.mod file:
go mod init github.com/yourusername/yourproject
Replace the module path with your actual repository URL. If you are working inside a subdirectory (e.g., cmd/myapp), you must change to the root directory first before running build commands:
cd ../../
go build ./cmd/myapp
Alternatively, if you are in a subdirectory but want to build a specific package relative to the module root, you can specify the path explicitly without changing directories, provided the go.mod exists in the parent tree:
go build ./cmd/myapp
If you are cloning an existing repository and still see this error, ensure you haven't accidentally deleted the file or that your .gitignore isn't excluding it (though go.mod should never be ignored). If the repository uses Go modules but the file is missing from your local clone, re-clone or check out the correct branch.
For legacy projects that don't use modules, you might be running this in an environment where GO111MODULE is forced to on. You can temporarily disable module mode for old projects by setting the environment variable, though migrating to modules is the recommended long-term fix:
GO111MODULE=off go build .
Remember that go mod tidy is often needed after adding new dependencies to ensure the go.mod and go.sum files are up to date, but it will fail if go.mod doesn't exist yet. Always verify your working directory with pwd (Linux/macOS) or cd (Windows) to confirm you are at the project root before running go commands.