Community编程与开发github.com

samber/golang-refactoring

Go 语言重构 — 安全、大规模地重构现有 Go 代码:提供覆盖适应性安全网、行为保持转换(gopls 重命名/提取、`gofmt -r`、`gopatch`)、映射到 Go 的 Fowler 重构目录、打破导入循环以及小型堆叠 PR。适用于函数或类型体积过大、代码异味阻碍功能开发或用户要求重构 Go 代码的场景 — 也可用于大规模重命名、提取函数或接口、在包之间移动代码或规划多步骤重构。

golang-refactoring 是什么?

该技能定义了专业 Go 重构工程师的角色和操作规范,专注于对现有 Go 代码进行安全、大规模的结构性变更。其核心理念是通过一系列小步骤实现重构,每一步都严格分离结构变更和行为变更,并确保不改变可观察行为。技能强调使用 gopls、`gofmt -r`、`eg` 和 `gopatch` 等工具驱动的行为保持转换,而非人工编辑,以提高安全性和可靠性。 该技能支持多种操作模式,包括用于分析影响的计划模式、需要一个一个人工签核的逐步执行模式、用于简单全局机械性变更的快速扫描模式,以及用于审查重构 PR 的审查模式。它严格执行硬性规则,例如绝不在同一个提交或 PR 中混合结构和行为变更,优先使用 gopls 的重命名/内联功能,并在需要跨多个站点进行重复更改时生成重写工具。该技能还集成了 `samber/cc-skills-golang@golang-gopls` 等关联技能以完成 gopls 设置。 为了确保安全性,技能要求在开始之前对受影响的代码区域进行测试覆盖分析,并根据覆盖水平(高/中/低)采取不同的策略,包括为未测试的代码编写特征测试。重构过程遵循“理解 → 安全网 → 小步工具驱动 → 验证 → 原子单类别提交”的核心循环,每个 PR 的目标代码行数控制在 100-500 行之间,以确保可审查性。

兼容平台✓Claude Code✓Codex CLI~Cursor
npx skills add https://github.com/samber/cc-skills-golang/tree/main/skills/golang-refactoring

Installed? Explore more 编程与开发 skills: steipete/bluebubbles, steipete/eightctl, steipete/blucli · View all 6 →

在你喜欢的 AI 中提问

打开一个已预加载此 Agent Skill 的新对话。

文档

社区默认技能。 任何明确覆盖 samber/cc-skills-golang@golang-refactoring 技能的公司技能将具有更高优先级。

角色: 你是一名 Go 重构工程师。你绝不在同一步骤中同时更改结构和行为 — 你需要保持测试网络检绿,优先使用行为保持工具而非手工编辑,并将更改拆分为小型、可评审的 PR。

思考模式: 在规划/排序步骤中尽可能进行彻底推理 — 映射影响范围、安排 PR 顺序以避免合并冲突、以及判断重构的哪些部分可以安全并行处理,这些都对浅层推理构成惩罚,因为错误的排序表现为构建失败或充满冲突的合并,而非明显的错误计划。在 Claude Code 中,使用 ultrathink 显式触发扩展思考。

编排模式: 仅在执行简单的单次机械性扫描时使用 ultracode/Workflows — 一次树级应用的 gofmt -r/eg/modernize 修复器,验证其为绿色,且没有步骤依赖于其他步骤。不要将其用于需要逐步的人工审阅和合并之间的多步骤重构:Workflows 是代理之间的运行,阶段之间没有人工检查点,而这正是分阶段重构在每次合并之间所必需的。

模式:

  • 计划模式(任何编辑前的强制性关卡)— 使用 gopls 映射结构和影响范围,构建重构清单,决定顺序,并在修改代码前获得用户明确签核。参见 workflow.md。
  • 执行模式(人在回路中)— 每个原子变更对应一个子代理、一个工作树、一个分支、一个 PR,并落地到重构分支上;当文件不重叠时并行,重叠时串行。将每个变更分派给一个子代理,只保留其结果 — 编排会话的上下文必须能够跨越清单中的每一行。参见 workflow.md。
  • 快速扫描模式 — 一个全局应用的、行为保持的机械性转换;可以使用 ultracode。
  • 审查模式 — 审查重构 PR:在批准前验证结构和行为的分离以及行为保持。

提问: 此技能中的签核关卡(计划模式的初始批准,以及下面每一步中重构的检查点)应通过环境的提问工具提出,绝不以读者可能略过的纯文本形式呈现 — 重构恰好是一种工作流,其中被忽略的“假设同意”代价高昂且难以撤销。这些是关乎不可逆决策的批准关卡,而非随意的澄清性问题,因此在下面每一点重复“通过提问工具询问”是有意为之,而非模板套话。

依赖项: gopls(主要执行器)— go install golang.org/x/tools/gopls@latest。可选:golangci-lint、benchstat、deadcode、eg、gopatch。完整的 gopls 设置和 MCP 注册 → 参见 samber/cc-skills-golang@golang-gopls 技能 — 这是本技能解释如何获取 gopls 的唯一位置;本技能中所有其他对 gopls 的引用均假定其已安装。

Go 重构 — 大规模安全变更

  • 重构(Fowler)是在不改变可观察行为的前提下,改变代码内部结构,使其更易理解或更易修改。
  • Go 工具链可以按构造证明多种转换是行为保持的 — 例如,gopls 会拒绝一个重命名,而非冒构建失败的风险。
  • 这种保证对于反射可以触及的任何内容(结构体标签、text/template 字段引用)是无效的 — 安全网仍然很重要。

核心循环

理解 → 安全网 → 小步骤工具驱动 → 验证 → 原子单类别提交。 重复。

  1. 理解 — 在接触任何代码之前,使用 gopls(引用、调用层次结构、包 API)映射变更的影响范围。
  2. 安全网 — 在覆盖不足的代码上进行修改之前,首先添加测试。
    • 基于_影响范围_的测试覆盖(而非全局覆盖)来制定策略。
    • 将编写该测试视为你检查变更的自身机制 — 而非留给评审者的形式主义。你自己编写的绿色测试套件才能真正让你区分“这是行为保持的”和“我希望这是行为保持的”。
    • 参见 safety-net.md 了解高/中/低的阈值以及针对未测试代码的特征测试方法。
  3. 小步骤工具驱动 — 优先使用机械的、工具驱动的转换而非手工编辑。参见 go-tooling.md 和 catalog.md。
  4. 验证 — go build ./... && go vet ./... && go test ./...;对于并发更改添加 -race,对于热点路径使用 benchstat 支持的 -bench。
  5. 原子单类别提交 — 提交纯粹是结构性的或纯粹是行为性的,绝不兼而有之。

硬性规则

  • 绝不在一个提交或 PR 中混合结构性和行为性变更。
    • 一个评审者为了正确性而审查重命名,与一个评审者为了副作用而审查功能,需要不同的姿态。
    • 混合两者会迫使一个评审者同时扮演两个角色,而纯粹的重命名所应得的快速、低审查度的评审将因此丧失。
  • 将代码移动与代码优化拆分为两个顺序执行的 PR,即使两者都是结构性的。
    • 它们需要不同的验证 — 移动由 gopls 加构建/测试证明安全,优化则需要基准测试和更仔细的正确性审查。
    • 两者修改相同的代码,因此应顺序执行而非在并行工作树中执行;并行化只是将冲突推迟到合并时。
    • 目标为每个 PR 100-500 行:足够小以便一次会议内完成评审,又足够大以便仍能作为一套连贯的变更来阅读。
  • 优先使用 gopls 的重命名/内联功能,而非 LLM 手工编辑。
    • 两者都是按构造保持行为的 — 重命名在遇到遮蔽、接口满足性破坏或格式错误的代码时会拒绝执行,而非静默产生有问题的差异;内联会将带副作用的参数替换为 var 临时变量,而非复制它们。
    • 在数十个调用点进行手工编辑则没有这样的保证,并且会明显遗漏某些情况。
  • 当变更在多个站点重复出现时,生成一个重写工具,而非手工编辑每个站点。
    • 按能力递增的顺序升级:gofmt -r → eg → gopatch → go/analysis 修复器(参见 go-tooling.md)。

Individual skills in this repo

This repo contains 20 individual skills — each has its own dedicated page.

samber/golang-benchmark

Golang benchmarking, profiling, and performance measurement. Use when writing, running, or comparing Go benchmarks, profiling hot paths with pprof, interpreting CPU/memory/trace profiles, analyzing results with benchstat, setting up CI benchmark regression detection, or investigating production performance with Prometheus runtime metrics. Also use when the developer needs deep analysis on a specific performance indicator - this skill provides the measurement methodology, while `samber/cc-skills-golang@golang-performance` provides the optimization patterns.

samber/golang-cli

Golang CLI application development. Use when building, modifying, or reviewing a Go CLI tool — especially for command structure, flag handling, configuration layering, version embedding, exit codes, I/O patterns, signal handling, shell completion, argument validation, and CLI unit testing. Also triggers when code uses cobra, viper, or urfave/cli. For cobra-specific APIs → See `samber/cc-skills-golang@golang-spf13-cobra` skill; for viper configuration layering → See `samber/cc-skills-golang@golang-spf13-viper` skill.

samber/golang-code-style

Golang code style conventions — line length and breaking, variable declarations, control flow clarity, when comments help vs hurt. Use when writing or reviewing Go code, asking about style or clarity, or establishing project coding standards. Not for naming conventions (→ See `samber/cc-skills-golang@golang-naming` skill), linter configuration (→ See `samber/cc-skills-golang@golang-lint` skill), or doc comments (→ See `samber/cc-skills-golang@golang-documentation` skill).

samber/golang-concurrency

Golang concurrency patterns. Use when writing or reviewing concurrent Go code involving goroutines, channels, select, locks, sync primitives, errgroup, singleflight, worker pools, or fan-out/fan-in pipelines. Also triggers when you detect goroutine leaks, race conditions, channel ownership issues, or need to choose between channels and mutexes.

samber/golang-context

Idiomatic context.Context usage in Golang — propagation through API boundaries, cancellation, timeouts and deadlines, request-scoped values, context.WithoutCancel for background work outliving requests. Apply when designing context propagation across layers, debugging leaked or unexpired contexts, choosing between context.Background/TODO/WithoutCancel, or storing values in context. Not for code that merely accepts ctx as first parameter.

samber/golang-continuous-integration

CI/CD pipeline configuration using GitHub Actions for Golang projects — testing, linting, SAST, security scanning, code coverage, Dependabot, Renovate, GoReleaser, code review automation, and release pipelines. Use when setting up or improving Go project CI, configuring GitHub Actions workflows, adding linters or security scanners, automating dependency updates, or adding quality gates.

samber/golang-database

Comprehensive guide for Go database access — parameterized queries, struct scanning, NULLable columns, transactions, isolation levels, SELECT FOR UPDATE, connection pool, batch processing, context propagation, and migration tooling. Use when writing, reviewing, or debugging Golang code that interacts with PostgreSQL, MariaDB, MySQL, or SQLite; for database testing; or for questions about database/sql, sqlx, or pgx. Does NOT generate database schemas or migration SQL.

samber/golang-data-structures

Golang data structures — slices (internals, capacity growth, preallocation, slices package), maps (internals, hash buckets, maps package), arrays, container/list/heap/ring, strings.Builder vs bytes.Buffer, generic collections, pointers (unsafe.Pointer, weak.Pointer), and copy semantics. Use when choosing or optimizing Go data structures, implementing generic containers, using container/ packages, unsafe or weak pointers, or questioning slice/map internals.

samber/golang-dependency-injection

Comprehensive guide for dependency injection (DI) in Golang. Covers why DI matters (testability, loose coupling, separation of concerns, lifecycle management), manual constructor injection, and DI library comparison (google/wire, uber-go/dig, uber-go/fx, samber/do). Use this skill when designing service architecture, setting up dependency injection, refactoring tightly coupled code, managing singletons or service factories, or when the user asks about inversion of control, service containers, or wiring dependencies in Go. For a specific DI library, → See `samber/cc-skills-golang@golang-google-wire`, `samber/cc-skills-golang@golang-uber-dig`, `samber/cc-skills-golang@golang-uber-fx`, or `samber/cc-skills-golang@golang-samber-do` skills.

samber/golang-dependency-management

Dependency management strategies for Golang projects — go.mod management, installing/upgrading packages, Minimal Version Selection, vulnerability scanning, outdated dependency tracking, binary size analysis, Dependabot/Renovate setup, conflict resolution, and go.work workspaces. Use when adding, removing, or upgrading Go dependencies, auditing vulnerabilities, resolving version conflicts, or setting up automated dependency updates.

samber/golang-design-patterns

Idiomatic Golang design patterns — functional options, constructors, error flow and cascading, resource management and lifecycle, graceful shutdown, resilience, architecture, dependency injection, data handling, streaming, and more. Apply when explicitly choosing between architectural patterns, implementing functional options, designing constructor APIs, setting up graceful shutdown, applying resilience patterns, or asking which idiomatic Go pattern fits a specific problem.

samber/golang-documentation

Comprehensive documentation guide for Golang projects, covering godoc comments, README, CONTRIBUTING, CHANGELOG, Go Playground, Example tests, API docs, and llms.txt. Use when writing or reviewing doc comments, documentation, adding code examples, setting up doc sites, or discussing documentation best practices. Triggers for both libraries and applications/CLIs.

samber/golang-error-handling

Idiomatic Golang error handling — creation, wrapping with %w, errors.Is/As, errors.Join, custom error types, sentinel errors, panic/recover, the single handling rule, structured logging with slog, HTTP request logging middleware, and samber/oops for production errors. Built to make logs usable at scale with log aggregation 3rd-party tools. Apply when creating, wrapping, inspecting, or logging errors in Go code. For samber/oops specifics → See `samber/cc-skills-golang@golang-samber-oops` skill; for slog handler ecosystem → See `samber/cc-skills-golang@golang-samber-slog` skill.

samber/golang-google-wire

Compile-time dependency injection in Golang using google/wire — wire.NewSet, wire.Build, wire.Bind (interface→concrete), wire.Struct, wire.Value, wire.InterfaceValue, wire.FieldsOf, cleanup functions, //go:build wireinject injector files, and generated wire_gen.go. Apply when using or adopting google/wire, when the codebase imports `github.com/google/wire`, or when wiring an application graph at compile time via `wire.Build`. For runtime DI with reflection, see `samber/cc-skills-golang@golang-uber-dig` skill.

samber/golang-gopls

Golang semantic code intelligence via `gopls`, the official Go language server — go-to-definition, find references, call/implementation hierarchy, workspace symbol search, package API discovery, diagnostics, safe rename, refactors (extract/inline/fill/rewrite code actions), formatting, and generated tests. Reaches an agent via gopls's own MCP server (`go_*` tools), Claude Code's native `LSP` tool, or the `gopls` CLI. Use when navigating or refactoring Go code — jumping to a definition, finding call sites before a rename, understanding a file's or package's dependencies, running diagnostics after an edit, or extracting/inlining/renaming. Not for the published ecosystem — packages not in your `go.mod`, versions, licenses, importers — → See `samber/cc-skills-golang@golang-pkg-go-dev` skill (`godig`). Not for a whole-tree vulnerability audit → See `samber/cc-skills-golang@golang-security` skill (`govulncheck`).

samber/golang-graphql

Implements GraphQL APIs in Golang using gqlgen or graphql-go. Apply when building GraphQL servers, designing schemas, writing resolvers, handling subscriptions, or integrating GraphQL with existing Go HTTP services. Also apply when the codebase imports `github.com/99designs/gqlgen` or `github.com/graph-gophers/graphql-go`.

samber/golang-grpc

Provides gRPC usage guidelines, protobuf organization, and production-ready patterns for Golang microservices. Use when implementing, reviewing, or debugging gRPC servers/clients, writing proto files, setting up interceptors, handling gRPC errors with status codes, configuring TLS/mTLS, testing with bufconn, or working with streaming RPCs.

samber/golang-how-to

Golang skills orchestrator — always active on any Golang coding, review, debug, or setup task. Reads the task context and loads the most relevant skills from samber/cc-skills-golang, often multiple at once: writing a gRPC service loads golang-grpc + golang-testing + golang-error-handling; debugging a panic loads golang-troubleshooting + golang-safety; auditing security loads golang-security + golang-lint + golang-safety. Also: disambiguates competing clusters when two skills seem to overlap (performance vs benchmark vs troubleshooting, samber/lo vs mo vs ro, DI cluster, safety vs security), and configures the project's agent-config file (CLAUDE.md, AGENTS.md, GEMINI.md, Cursor rules, or Copilot instructions) to force-trigger skills in a project (/golang-how-to configure).

samber/golang-lint

Linting best practices and golangci-lint configuration for Golang projects — running linters, configuring .golangci.yml, suppressing warnings with nolint directives, interpreting lint output, and selecting linters. Use when configuring golangci-lint, asking about lint warnings or nolint suppressions, setting up code quality tooling, or choosing linters. Also use when the user mentions golangci-lint, go vet, staticcheck, or revive.

samber/golang-modernize

Modernize Golang code to use recent language features, standard library improvements, and idiomatic patterns. Trigger proactively when writing or reviewing Go code and old-style patterns are detected, or when encountering a deprecation warning. Also use when the user explicitly asks for modernization, a Go version upgrade, or a CI/tooling refresh.

相关技能