Community程式設計與開發github.com

samber/golang-refactoring

Go 重構 — 安全、大規模地重組現有 Go 程式碼:涵蓋測試覆蓋率調適的安全網、行為保留轉換(gopls Rename/Extract、`gofmt -r`、`gopatch`)、對應 Go 語言的 Fowler 重構目錄、打破導入循環,以及小型的堆疊 PR。

golang-refactoring 是什麼?

這是一個專為 Go 語言設計的專業重構技能,旨在安全、大規模地重組現有程式碼。它的核心原則是不變更可觀察的行為,並透過行為保留的工具(如 gopls 的 Rename/Extract、`gofmt -r`、`gopatch`)來減少手動編輯的風險。技能內建了一個「理解 → 建立安全網 → 小步驟工具驅動 → 驗證 → 原子單類別提交」的核心循環,並嚴格要求結構性變更與行為變更不得混在同一個 commit 或 PR 中,以確保審查的正確性與效率。 此技能主要用於 Claude Code 等 AI 代理平台,支援「規劃模式」、「執行模式」、「簡單掃描模式」與「審查模式」等多種操作模式。它擅長處理的場景包括:函式或型別過於龐大、程式碼異味阻礙新功能、需要大規模重新命名、提取函式或介面、在套件之間搬移程式碼,或規劃多步驟的重構流程。對於單純的重新命名、專案佈局拆分、現代化改寫、程式碼風格調整或設計模式導入等任務,則建議參考其他相關技能。

相容平台✓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,落地到重構分支上;當檔案不重疊時可並行,當檔案重疊時則依序進行。將每個變更分派給一個子代理,並僅保留其結果 — 協調 session 的上下文必須能持續到清單中的每一行。請參閱 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 的唯一位置;本技能中對其的所有其他引用都假設它已安裝。

Go 重構 — 安全地大規模變更

  • 重構(Fowler)是在不變更可觀察行為的前提下,變更程式碼的內部結構,使其更容易理解或更便宜地修改。
  • Go 工具可以證明某些轉換天生是行為保留的 — 例如,gopls 會拒絕 Rename,而不是冒著建置失敗的風險。
  • 這個保證對任何反射可以觸及的內容(結構體標籤、text/template 欄位引用)是無效的 — 安全網仍然很重要。

核心循環

理解 → 安全網 → 小型工具驅動步驟 → 驗證 → 原子單類別提交。 重複。

  1. 理解 — 在觸碰任何東西之前,使用 gopls 繪製變更的影響範圍(引用、呼叫層次、套件 API)。
  2. 安全網 — 在觸碰覆蓋率不足的程式碼之前,先添加測試。
    • 根據_影響範圍的_測試覆蓋率,而非全域覆蓋率,來決定策略。
    • 將撰寫該測試視為你自己檢查變更的機制 — 而不是留給審查者的形式流程。你自己撰寫並通過的綠色測試套組,才能讓你區分「這是行為保留的」與「我希望這是行為保留的」。
    • 請參閱 safety-net.md 了解 HIGH/MEDIUM/LOW 的閾值以及針對未測試程式碼的特性測試配方。
  3. 小型工具驅動步驟 — 偏好使用機械式、工具驅動的轉換,而非手動編輯。請參閱 go-tooling.md 和 catalog.md。
  4. 驗證 — go build ./... && go vet ./... && go test ./...;針對並發變更添加 -race,針對熱門路徑添加 benchstat 支援的 -bench。
  5. 原子單類別提交 — 提交內容純粹是結構性的或純粹是行為性的,絕不能兩者兼具。

硬性規則

  • 絕不在一個 commit 或 PR 中混合結構性和行為性變更。
    • 審查者以不同的姿態審查重新命名的正確性與審查功能是否有副作用。
    • 將兩者混合會迫使一位審查者同時扮演兩種角色,而純粹重新命名所應得的快速、低審查度的審查就會被遺漏。
  • 將程式碼搬移與程式碼最佳化拆分為兩個依序的 PR,即使兩者都是結構性的。
    • 它們需要不同的驗證 — 搬移透過 gopls 加上建置/測試證明是安全的,最佳化則需要基準測試和更仔細的正確性檢查。
    • 它們觸及相同的程式碼,因此應依序運行,而不是在並行工作目錄中運行;平行化只會將衝突轉移到合併時。
    • 目標是每個 PR 100–500 行:要小到可以一次性審查完成,但又大到仍然可以視為一個連貫的變更。
  • 偏好使用 gopls Rename/Inline 而非 LLM 的手動編輯。
    • 兩者天生都是行為保留的 — Rename 會在陰影、介面滿足性中斷或格式錯誤的程式碼時拒絕,而不是默默地產生一個錯誤的 diff;Inline 會將具有副效應的參數替換為 var 臨時變數,而不是複製它們。
    • 跨數十個呼叫點的手動編輯則沒有這樣的保證,並且明顯會遺漏案例。
  • 當變更在多個位置重複發生時,應生成重寫工具,而不是手動編輯每個位置。
    • 按功能增強順序升級 gofmt -r → eg → gopatch → go/analysis 修復器(請參閱 go-tooling.md)。
  • 將重構提交建立到共享的重構分支上,該分支基於你需要的最終目標分支(例如 main 或 release/...)。
    • 這樣,你可以在合併到目標分支之前,使用 main 的最新變更來 rebase 整個系列。
    • 建立一個追蹤分支,但不要將其推送到遠端,直到需要審查為止 — 使用本地的輕量級標籤來追蹤位置。
  • 在審查之前,使用 git rebase -i 清理提交歷史。
    • 將 Fix typo、oops、WIP 等 squash 在一起。目標是每個結構性變更一個提交,乾淨且有意義。
  • 將變更劃分為檔案不相交的 PR 以實現完全平行化。
    • 如果兩個重構觸及完全不同的 Go 套件,它們可以同時在不同的分支上進行,並且永遠不會衝突。
    • 如果它們觸及同一個套件但不同的檔案,仍然可能存在合併衝突(例如,一個檔案導入了一個另一個 PR 刪除了的套件)。謹慎行事。

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.

相關技能