modules Flashcards
(10 cards)
What is a Go Module?
A collection of related Go packages with versioned dependencies
Key Files:
* go.mod (declares module path and dependencies)
* go.sum (records cryptographic checksums)
module github.com/yourname/project go 1.21 require ( github.com/pkg/errors v0.9.1 golang.org/x/sync v0.3.0 )
Initializing a Module
go mod init github.com/yourname/project
What it does:
Creates a go.mod file in your project root.
Rule:
Module path should match your code’s import path.
Adding Dependencies
Automatically:
Just import in code and run:
go mod tidy
Manually:
go get github.com/pkg/errors@v0.9.1
Key Flags:
@latest - gets newest version
@v1.2.3 - specific version
go mod tidy
Purpose:
Adds missing dependencies
Removes unused dependencies
Updates go.mod/go.sum
Always run this:
After changing imports or before committing.
Upgrading/Downgrading
Check versions:go list -m -versions github.com/pkg/errors
Upgrade:go get github.com/pkg/errors@latest
Downgrade:go get github.com/pkg/errors@v0.8.1
Vendor Directory
Create vendor/:go mod vendor
Use vendor/:go build -mod=vendor
Purpose:
Stores dependency copies locally for reproducibility.
Version Selection
How Go chooses versions:
1. Highest compatible semver tag (e.g., v2.3.4)
2. Pseudo-versions (e.g., v0.0.0-20231012000000-abc123)
Key Terms:
* Minimal version selection (MVS)
* Semantic Import Versioning (major versions ≥2 change import paths)
Replacing Dependencies
In go.mod:
replace (
github.com/old/mod => ../local/mod
golang.org/x/net => github.com/golang/net v0.7.0
)
Use Cases:
* Local development
* Forked dependencies
Module Proxy
Default Proxy:
proxy.golang.org (Google-run)
Environment Variables:
GOPROXY=https://proxy.golang.org,direct
GOPRIVATE=github.com/yourcompany/* (skip proxy for private repos)
Key Commands Cheat Sheet
Command Purpose
go mod init Initialize new module
go mod tidy Sync dependencies
go get -u Update dependencies
go list -m all View all dependencies
go mod why Explain why a dependency exists
go mod graph Print dependency graph
Golden Rule:
Always commit both go.mod and go.sum to version control!