go.mod Formatting Best Practices
Learn go.mod formatting conventions and best practices: tab indentation, version alignment, block organization, and the canonical format produced by go mod tidy.
Detailed Explanation
go.mod Formatting Best Practices
Following consistent formatting conventions makes go.mod files readable, maintainable, and merge-friendly. These practices align with the canonical format produced by go mod tidy.
Canonical Format
The Go toolchain defines a canonical go.mod format:
module github.com/example/project
go 1.22.0
require (
github.com/gin-gonic/gin v1.9.1
github.com/spf13/cobra v1.8.0
golang.org/x/text v0.14.0
)
require (
github.com/bytedance/sonic v1.10.0 // indirect
golang.org/x/crypto v0.17.0 // indirect
)
Key Conventions
1. Tab Indentation Entries within blocks use a single tab for indentation. Spaces are used only for version alignment after the module path.
2. Version Alignment Within a require block, version numbers are aligned to the same column using spaces after the module path.
3. Block Organization
moduledirective firstgo(and optionaltoolchain) directive second- Direct
requireblock third - Indirect
requireblock fourth replacedirectives (if any)excludedirectives (if any)retractdirectives (if any)
4. Blank Lines One blank line between each block/section. No blank lines within a block.
5. Alphabetical Sorting Entries within each block sorted by module path.
Pre-commit Hook
Add a formatting check to your Git pre-commit hook:
# Check if go.mod is properly formatted
go mod tidy
git diff --exit-code go.mod go.sum
CI Integration
In your CI pipeline:
- name: Check go.mod formatting
run: |
go mod tidy
git diff --exit-code go.mod go.sum
Common Anti-Patterns
- Mixing tabs and spaces for indentation
- Not separating direct and indirect dependencies
- Random ordering of require entries
- Stale replace directives left from local development
- Commented-out require entries (just remove them)
Editor Configuration
Most Go-aware editors format go.mod automatically. For VS Code with the Go extension, formatting happens on save.
Use Case
Adopting consistent formatting practices reduces friction in code reviews and minimizes merge conflicts. Teams that enforce go.mod formatting through CI and pre-commit hooks spend less time on formatting discussions and more time on actual dependency decisions. The online formatter provides a quick way to clean up go.mod files without needing local Go tooling.