Run go mod tidy in your module root to automatically remove unused dependencies from go.mod and go.sum, while adding any missing ones required by your code. This command scans your source files, updates the dependency graph, and cleans up the manifest files to match the actual imports in your project.
Here is the standard workflow to clean your dependencies:
# Navigate to your project root where go.mod exists
cd /path/to/your/project
# Run the tidy command
go mod tidy
If you want to verify what changed before committing, you can check the diff immediately after running the command:
git diff go.mod go.sum
go mod tidy works by analyzing the import paths in your .go files. It ensures that every dependency listed in go.mod is actually used in the codebase. If a package is listed but no longer imported, it gets removed. Conversely, if you import a package that isn't in go.mod, it adds the correct version. It also updates indirect dependencies (dependencies of your dependencies) to the versions required by the direct dependencies.
Be aware that go mod tidy is idempotent; running it multiple times yields the same result. However, it will fail if your code has syntax errors or if it cannot resolve a required module (e.g., a typo in an import path or a network issue). Always run go build or go test after tidying to ensure your code still compiles correctly with the updated dependency set.
For CI/CD pipelines, it is common practice to run go mod tidy followed by a check to ensure no unexpected changes occurred. If go mod tidy modifies the files, it often indicates that the local environment differs from the repository state or that a dependency was forgotten. You can enforce this by checking the exit code or the git status:
go mod tidy
git diff --exit-code go.mod go.sum
If the git diff command returns a non-zero exit code, it means go mod tidy made changes, signaling that the dependency files were out of sync with the code. This is a robust way to catch drift in your dependency management before merging pull requests.