golang-dependency-management

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese
Persona: You are a Go dependency steward. You treat every new dependency as a long-term maintenance commitment — you ask whether the standard library already solves the problem before reaching for an external package.
角色定位: 你是一名Go依赖管理专员。你将每个新依赖都视为长期维护承诺——在选择外部包之前,你会先确认标准库是否已经能解决该问题。

Go Dependency Management

Go依赖管理

AI Agent Rule: Ask Before Adding Dependencies

AI Agent规则:添加依赖前先询问

Before running
go get
to add any new dependency, AI agents MUST ask the user for confirmation.
AI agents can suggest packages that are unmaintained, low-quality, or unnecessary when the standard library already provides equivalent functionality. Using
go get -u
to upgrade an existing dependency is safe.
Before proposing a dependency, present:
  • Package name and import path
  • What it does and why it's needed
  • Whether the standard library covers the use case
  • GitHub stars, last commit date, and maintenance status (check via
    gh repo view
    )
  • License compatibility
  • Known alternatives
The
samber/cc-skills-golang@golang-popular-libraries
skill contains a curated list of vetted, production-ready libraries. Prefer recommending packages from that list. When no vetted option exists, favor well-known packages from the Go team (
golang.org/x/...
) or established organizations over obscure alternatives.
在运行
go get
添加任何新依赖之前,AI Agent必须先请求用户确认。
当标准库已经提供等效功能时,AI Agent可能会建议那些无人维护、质量低下或不必要的包。使用
go get -u
升级现有依赖是安全的。
在推荐依赖之前,请提供以下信息:
  • 包名称和导入路径
  • 功能用途及必要性
  • 标准库是否覆盖该使用场景
  • GitHub星标数、最后提交日期及维护状态(可通过
    gh repo view
    查询)
  • 许可证兼容性
  • 已知替代方案
samber/cc-skills-golang@golang-popular-libraries
技能包含经过筛选的、可用于生产环境的库列表。优先推荐该列表中的包。如果没有经过筛选的选项,优先选择Go团队(
golang.org/x/...
)或知名组织的包,而非小众替代方案。

Key Rules

核心规则

  • go.sum
    MUST be committed — it records cryptographic checksums of every dependency version, letting
    go mod verify
    detect supply-chain tampering. Without it, a compromised proxy could silently substitute malicious code
  • govulncheck ./...
    before every release — catches known CVEs in your dependency tree before they reach production
  • Check maintenance status, license, and stdlib alternatives before adding a dependency — every dependency increases attack surface, maintenance burden, and binary size
  • go mod tidy
    before every commit that changes dependencies — removes unused modules and adds missing ones, keeping go.mod honest
  • 必须提交
    go.sum
    文件——它记录了每个依赖版本的加密校验和,让
    go mod verify
    能够检测供应链篡改。没有它,受 compromise 的代理可能会悄悄替换恶意代码
  • 每次发布前运行
    govulncheck ./...
    ——在漏洞进入生产环境前捕获依赖树中的已知CVE
  • 添加依赖前检查维护状态、许可证和标准库替代方案——每个依赖都会增加攻击面、维护负担和二进制文件大小
  • 每次修改依赖的提交前运行
    go mod tidy
    ——移除未使用的模块并添加缺失的模块,保持go.mod的准确性

go.mod & go.sum

go.mod & go.sum

Essential Commands

核心命令

CommandPurpose
go mod tidy
Add missing deps, remove unused ones
go mod download
Download modules to local cache
go mod verify
Verify cached modules match go.sum checksums
go mod vendor
Copy deps into
vendor/
directory
go mod edit
Edit go.mod programmatically (scripts, CI)
go mod graph
Print the module requirement graph
go mod why
Explain why a module or package is needed
命令用途
go mod tidy
添加缺失的依赖,移除未使用的依赖
go mod download
将模块下载到本地缓存
go mod verify
验证缓存中的模块与go.sum的校验和是否匹配
go mod vendor
将依赖复制到
vendor/
目录
go mod edit
以编程方式编辑go.mod(脚本、CI场景)
go mod graph
打印模块依赖关系图
go mod why
解释某个模块或包被需要的原因

Vendoring

依赖 vendoring

Use
go mod vendor
when you need hermetic builds (no network access), reproducibility guarantees beyond checksums, or when deploying to environments without module proxy access. CI pipelines and Docker builds sometimes benefit from vendoring. Run
go mod vendor
after any dependency change and commit the
vendor/
directory.
当你需要封闭构建(无网络访问)、超出校验和的可重复性保证,或者部署到无模块代理访问的环境时,可以使用
go mod vendor
。CI流水线和Docker构建有时会从vendoring中受益。每次依赖变更后运行
go mod vendor
并提交
vendor/
目录。

Installing & Upgrading Dependencies

安装与升级依赖

Adding a Dependency

添加依赖

bash
go get github.com/pkg/errors           # Latest version
go get github.com/pkg/errors@v0.9.1    # Specific version
go get github.com/pkg/errors@latest    # Explicitly latest
go get github.com/pkg/errors@master    # Specific branch (pseudo-version)
bash
go get github.com/pkg/errors           # 最新版本
go get github.com/pkg/errors@v0.9.1    # 指定版本
go get github.com/pkg/errors@latest    # 明确获取最新版本
go get github.com/pkg/errors@master    # 指定分支(伪版本)

Upgrading

升级依赖

bash
go get -u ./...            # Upgrade ALL direct+indirect deps to latest minor/patch
go get -u=patch ./...      # Upgrade to latest patch only (safer)
go get github.com/pkg@v1.5 # Upgrade specific package
Prefer
go get -u=patch
for routine updates — patch versions change no public API (semver promise), so they're unlikely to break your build. Minor version upgrades may add new APIs but can also deprecate or change behavior unexpectedly.
bash
go get -u ./...            # 将所有直接+间接依赖升级到最新的小版本/补丁版本
go get -u=patch ./...      # 仅升级到最新补丁版本(更安全)
go get github.com/pkg@v1.5 # 升级指定包
**优先使用
go get -u=patch
**进行常规更新——补丁版本不会修改公共API(语义化版本承诺),因此不太可能破坏构建。小版本升级可能会添加新API,但也可能意外弃用或更改行为。

Removing a Dependency

移除依赖

bash
go get github.com/pkg/errors@none   # Mark for removal
go mod tidy                          # Clean up go.mod and go.sum
bash
go get github.com/pkg/errors@none   # 标记为待移除
go mod tidy                          # 清理go.mod和go.sum

Installing CLI Tools

安装CLI工具

bash
go install github.com/golangci/golangci-lint/cmd/golangci-lint@latest
go install
builds and installs a binary to
$GOPATH/bin
. Use
@latest
or a specific version tag — never
@master
for tools you depend on.
bash
go install github.com/golangci/golangci-lint/cmd/golangci-lint@latest
go install
会构建二进制文件并安装到
$GOPATH/bin
。使用
@latest
或特定版本标签——对于你依赖的工具,绝不要使用
@master

The tools.go Pattern

tools.go 模式

Pin tool versions in your module without importing them in production code:
go
//go:build tools

package tools

import (
    _ "github.com/golangci/golangci-lint/cmd/golangci-lint"
    _ "golang.org/x/vuln/cmd/govulncheck"
)
The build constraint ensures this file is never compiled. The blank imports keep the tools in
go.mod
so
go install
uses the pinned version. Run
go mod tidy
after creating this file.
在模块中固定工具版本,而无需在生产代码中导入它们:
go
//go:build tools

package tools

import (
    _ "github.com/golangci/golangci-lint/cmd/golangci-lint"
    _ "golang.org/x/vuln/cmd/govulncheck"
)
构建约束确保该文件永远不会被编译。空白导入会将工具保留在go.mod中,因此
go install
会使用固定的版本。创建该文件后运行
go mod tidy

Deep Dives

深度指南

  • Versioning & MVS — Semantic versioning rules (major.minor.patch), when to increment each number, pre-release versions, the Minimal Version Selection (MVS) algorithm (why you can't just pick "latest"), and major version suffix conventions (v0, v1, v2 suffixes for breaking changes).
  • Auditing Dependencies — Vulnerability scanning with
    govulncheck
    , tracking outdated dependencies, analyzing which dependencies make the binary large (
    goweight
    ), and distinguishing test-only vs binary dependencies to keep
    go.mod
    clean.
  • Dependency Conflicts & Resolution — Diagnosing version conflicts (what
    go get
    does when you request incompatible versions), resolution strategies (
    replace
    directives for local development,
    exclude
    for broken versions,
    retract
    for published versions that should be skipped), and workflows for conflicts across your dependency tree.
  • Go Workspaces
    go.work
    files for multi-module development (e.g., library + example application), when to use workspaces vs monorepos, and workspace best practices.
  • Automated Dependency Updates — Setting up Dependabot or Renovate for automatic dependency update PRs, auto-merge strategies (when to merge automatically vs require review), and handling security updates.
  • Visualizing the Dependency Graph
    go mod graph
    to inspect the full dependency tree,
    modgraphviz
    to visualize it, and interactive tools to find which dependency chains cause bloat.
  • 版本控制与最小版本选择 —— 语义化版本规则(主版本.次版本.补丁版本)、各版本号的递增时机、预发布版本、最小版本选择(Minimal Version Selection)算法(为什么不能直接选“最新版本”)以及主版本后缀约定(破坏性变更使用v0、v1、v2后缀)。
  • 依赖审计 —— 使用
    govulncheck
    进行漏洞扫描、追踪过时依赖、分析哪些依赖导致二进制文件过大(
    goweight
    )、区分仅测试依赖与二进制依赖以保持go.mod简洁。
  • 依赖冲突与解决 —— 诊断版本冲突(当你请求不兼容版本时
    go get
    的行为)、解决策略(本地开发使用
    replace
    指令、排除损坏版本使用
    exclude
    、跳过已发布的问题版本使用
    retract
    )以及跨依赖树的冲突解决工作流。
  • Go工作区 —— 用于多模块开发的
    go.work
    文件(例如:库 + 示例应用)、何时使用工作区而非单体仓库,以及工作区最佳实践。
  • 自动依赖更新 —— 设置Dependabot或Renovate以自动生成依赖更新PR、自动合并策略(何时自动合并 vs 需要审核)以及处理安全更新。
  • 依赖图可视化 —— 使用
    go mod graph
    查看完整的依赖树、使用
    modgraphviz
    进行可视化,以及使用交互式工具查找导致体积膨胀的依赖链。

Cross-References

交叉参考

  • → See
    samber/cc-skills-golang@golang-continuous-integration
    skill for Dependabot/Renovate CI setup
  • → See
    samber/cc-skills-golang@golang-security
    skill for vulnerability scanning with govulncheck
  • → See
    samber/cc-skills-golang@golang-popular-libraries
    skill for vetted library recommendations
  • → 查看
    samber/cc-skills-golang@golang-continuous-integration
    技能了解Dependabot/Renovate的CI配置
  • → 查看
    samber/cc-skills-golang@golang-security
    技能了解使用govulncheck进行漏洞扫描的方法
  • → 查看
    samber/cc-skills-golang@golang-popular-libraries
    技能了解经过筛选的库推荐

Quick Reference

快速参考

bash
undefined
bash
undefined

Start a new module

初始化新模块

go mod init github.com/user/project
go mod init github.com/user/project

Add a dependency

添加依赖

go get github.com/pkg/errors@v0.9.1
go get github.com/pkg/errors@v0.9.1

Upgrade all deps (patch only, safer)

升级所有依赖(仅补丁版本,更安全)

go get -u=patch ./...
go get -u=patch ./...

Remove unused deps

移除未使用的依赖

go mod tidy
go mod tidy

Check for vulnerabilities

检查漏洞

govulncheck ./...
govulncheck ./...

Check for outdated deps

检查过时依赖

go list -u -m -json all | go-mod-outdated -update -direct
go list -u -m -json all | go-mod-outdated -update -direct

Analyze binary size by dependency

按依赖分析二进制文件大小

goweight
goweight

Understand why a dep exists

了解某个依赖被引入的原因

go mod why -m github.com/some/module
go mod why -m github.com/some/module

Visualize dependency graph

可视化依赖图

go mod graph | modgraphviz | dot -Tpng -o deps.png
go mod graph | modgraphviz | dot -Tpng -o deps.png

Verify checksums

验证校验和

go mod verify
undefined
go mod verify
undefined