How to Use Vendor Directory in Go for Dependency Management
vendor directory stores copies of your project’s dependencies locally. To use it, run go mod vendor to populate the directory, and Go will prioritize packages from vendor when building your project.Syntax
The vendor directory is a folder inside your Go project that holds copies of external packages your code depends on. To create or update this directory, use the command:
go mod vendor- copies all dependencies into thevendorfolder.
When you build or run your Go program, the Go tool automatically uses packages from vendor if it exists.
go mod vendor
Example
This example shows how to create a vendor directory and use it in a simple Go project.
package main import ( "fmt" "rsc.io/quote" ) func main() { fmt.Println(quote.Hello()) }
Common Pitfalls
Not running go mod vendor after adding dependencies: Your vendor folder won't update automatically, causing build errors.
Ignoring the vendor directory in version control: You should commit the vendor folder to ensure consistent builds across environments.
Using GOFLAGS=-mod=vendor incorrectly: This flag forces Go to use vendor but can cause errors if the directory is missing or incomplete.
/* Wrong: Not updating vendor after adding a new dependency */ // go get example.com/newdep // go build # fails if vendor not updated /* Right: Update vendor after adding dependency */ // go get example.com/newdep // go mod vendor // go build # succeeds using vendor
Quick Reference
| Command | Purpose |
|---|---|
| go mod vendor | Create or update the vendor directory with all dependencies |
| go build | Build the project using vendor if present |
| go run | Run the project using vendor if present |
| git add vendor/ | Add vendor directory to version control |
| GOFLAGS=-mod=vendor go build | Force Go to use vendor directory explicitly |
Key Takeaways
go mod vendor to create or update the vendor directory with your dependencies.GOFLAGS=-mod=vendor carefully to force vendor usage when needed.