Replace Directives in go.mod
Master go.mod replace directives for local development, forking dependencies, and version overrides. Learn single-line and block syntax with practical examples.
Detailed Explanation
Replace Directives
The replace directive in go.mod redirects a module to a different location or version. This is one of the most powerful and frequently used features for Go development workflows.
Basic Syntax
Single-line form:
replace github.com/original/module v1.2.3 => github.com/fork/module v1.2.4
Block form for multiple replacements:
replace (
github.com/original/module v1.2.3 => github.com/fork/module v1.2.4
github.com/other/module v0.5.0 => github.com/other/module v0.6.0
)
Common Use Cases
1. Local Development
replace github.com/myorg/shared-lib => ../shared-lib
Point a dependency to a local checkout for iterative development. No version needed for local paths.
2. Fork Replacement
replace github.com/original/lib v1.5.0 => github.com/myfork/lib v1.5.0-patched
Use a forked version while waiting for an upstream fix.
3. Version Override
replace github.com/vulnerable/lib v1.0.0 => github.com/vulnerable/lib v1.0.1
Force a specific version to patch a security vulnerability.
4. Unversioned Override
replace github.com/example/lib => github.com/example/lib v2.0.0-beta.1
Omitting the old version replaces ALL versions of the module.
Important Notes
- Replace directives only apply in the main module (not in dependencies)
- Local path replacements must use relative (
../) or absolute paths - The
go.sumfile is updated to reflect the replacement go mod tidywill not remove replace directives automatically
Formatting
The formatter aligns replace directives for readability, padding the left side so the => arrows line up:
replace (
github.com/short/path v1.0.0 => github.com/other/path v1.0.1
github.com/longer/path v2.3.0 => ../local-path
)
Use Case
Replace directives are essential during library development when you need to test changes to a dependency before publishing it. Teams working on microservices with shared libraries use local replaces daily. Security teams use version overrides to patch vulnerabilities immediately. The formatter ensures replace blocks stay clean and aligned as the team adds and removes replacements.