0
0
GoHow-ToBeginner · 3 min read

How to Use Vendor Directory in Go for Dependency Management

In Go, the 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 the vendor folder.

When you build or run your Go program, the Go tool automatically uses packages from vendor if it exists.

bash
go mod vendor
💻

Example

This example shows how to create a vendor directory and use it in a simple Go project.

go
package main

import (
	"fmt"
	"rsc.io/quote"
)

func main() {
	fmt.Println(quote.Hello())
}
Output
Hello, world.
⚠️

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.

bash
/* 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

CommandPurpose
go mod vendorCreate or update the vendor directory with all dependencies
go buildBuild the project using vendor if present
go runRun the project using vendor if present
git add vendor/Add vendor directory to version control
GOFLAGS=-mod=vendor go buildForce Go to use vendor directory explicitly

Key Takeaways

Run go mod vendor to create or update the vendor directory with your dependencies.
Go automatically uses the vendor directory when it exists during build and run commands.
Commit the vendor directory to version control to ensure consistent builds across machines.
Always update the vendor directory after adding or changing dependencies.
Use GOFLAGS=-mod=vendor carefully to force vendor usage when needed.