Go Modules & Dependencies

Module Commands

Essential go mod workflow
# Initialize a new module
go mod init github.com/evanusmodestus/netcheck

# Add a dependency
go get github.com/spf13/cobra@latest

# Pin to a specific version
go get github.com/spf13/cobra@v1.8.0

# Update all dependencies to latest minor/patch
go get -u ./...

# Update only patch versions
go get -u=patch ./...

# Remove unused, add missing
go mod tidy

# Copy dependencies into vendor/
go mod vendor

# Verify checksums
go mod verify

go mod tidy is the command you run most. It adds anything missing from go.mod/go.sum and removes anything unused.

go.mod and go.sum

Understanding the module files
// go.mod — human-editable, version-controlled
module github.com/evanusmodestus/netcheck

go 1.22

require (
    github.com/spf13/cobra v1.8.0
    github.com/spf13/pflag v1.0.5 // indirect
)

// go.sum — auto-generated, version-controlled
// Contains cryptographic checksums for every dependency
// DO NOT edit manually

Direct dependencies are listed in require. Indirect dependencies (transitive) are marked with // indirect. Both files should be committed.

Workspace Mode

Multi-module development with go.work
# Create a workspace
go work init ./netcheck ./netcheck-lib

# Add another module
go work use ./netcheck-ui
go.work file
go 1.22

use (
    ./netcheck
    ./netcheck-lib
    ./netcheck-ui
)

Workspaces let you develop multiple modules together without replace directives. Local changes in one module are immediately visible to others. Do not commit go.work to shared repositories.

Replace Directive

Override a dependency with a local copy
// go.mod
replace github.com/original/pkg => ../local-pkg

// Or a specific fork
replace github.com/original/pkg => github.com/myfork/pkg v0.0.0-20240101000000-abc123

replace is useful for debugging, forking, or local development. Remove it before publishing — consumers of your module will not inherit your replace directives.

Useful Inspection Commands

Querying dependencies
# Why is this dependency present?
go mod why github.com/some/dep

# Full dependency graph
go mod graph

# List all available versions of a module
go list -m -versions github.com/spf13/cobra

# Show current dependency versions
go list -m all

# Find which module provides a package
go list -m -json github.com/spf13/cobra

go mod why traces the import path from your code to the dependency — essential for understanding why go mod tidy keeps something you thought was unused.