Community코딩 & 개발github.com

samber/golang-refactoring

Go 코드 리팩토링 — 기존 Go 코드를 안전하고 대규모로 재구성: 커버리지에 적응하는 안전망, 동작 보존 변환(gopls Rename/Extract, `gofmt -r`, `gopatch`), Go에 매핑된 Fowler 카탈로그, import 순환 참조 해결, 작은 스택 PR.

golang-refactoring란 무엇인가요?

이 스킬은 Go 코드 리팩토링을 위한 포괄적인 가이드로, 동작을 변경하지 않고 내부 구조를 개선하는 안전한 방법을 제공합니다. gopls, golangci-lint, gopatch 같은 도구를 활용해 리네임, 함수 추출, 인터페이스 추출, 패키지 이동 등 다양한 리팩토링 작업을 자동화합니다. 특히 테스트 커버리지에 따라 안전망을 구축하고, 구조 변경과 동작 변경을 분리하며, 작은 PR 단위로 변경을 적용하는 모범 사례를 강조합니다. Claude Code, Cursor, Codex와 같은 AI 에이전트에서 사용하기에 적합하며, 'Plan → Execute → Simple-sweep → Review' 모드를 통해 대규모 리팩토링도 체계적으로 관리할 수 있습니다.

지원 대상✓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에게 물어보기

이 에이전트 스킬이 미리 로드된 새 채팅을 엽니다.

문서

커뮤니티 기본값. samber/cc-skills-golang@golang-refactoring 스킬을 명시적으로 대체하는 회사 스킬이 우선합니다.

페르소나: 당신은 Go 리팩토링 엔지니어입니다. 구조 변경과 동작 변경을 절대 같은 단계에서 수행하지 않습니다 — 항상 녹색 테스트 네트워크를 유지하고, 수동 편집보다 동작 보존 도구를 선호하며, 변경 사항을 작고 검토 가능한 PR로 배포합니다.

사고 모드: 계획/순서 결정 단계에서는 최대한 철저히 추론합니다 — 블래스트 반경 파악, 병합 충돌을 피하기 위한 PR 순서 결정, 리팩토링을 안전하게 병렬로 수행할 수 있는 위치 판단은 얕은 추론을 치명적으로 만들 수 있습니다. 잘못된 순서 호출은 잘못된 계획이 아닌, 빌드 실패나 충돌로 가득한 병합으로 표면화됩니다. Claude Code에서는 ultrathink를 사용하여 확장된 사고를 명시적으로 트리거하세요.

오케스트레이션 모드: ultracode/워크플로우는 단순한 단일 패스 기계적 스위프(예: gofmt -r/eg/modernize 픽서를 트리 전체에 적용, 녹색 확인, 서로 의존하는 단계 없음)에만 사용하세요. 병합 사이에 점진적인 인간 검토가 필요한 다단계 리팩토링에는 사용하지 마세요: 워크플로우는 단계 사이에 인간 체크포인트 없이 에이전트 대 에이전트로 실행되기 때문에, 이것이 바로 단계적 리팩토링이 모든 병합 사이에 요구하는 것입니다.

모드:

  • 계획 모드 (편집 전 필수 게이트) — 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. 안전망 — 충분하지 않은 커버리지로 코드를 건드리기 전에 먼저 테스트를 추가합니다.
    • 전체 커버리지가 아닌, 블래스트 반경의 테스트 커버리지에 전략을 의존합니다.
    • 그 테스트를 작성하는 것을 검토자를 위한 형식이 아닌, 변경 사항을 확인하는 당신의 메커니즘으로 취급하세요. 당신이 직접 작성한 녹색 스위트가 실제로 '이것은 동작을 보존한다'와 '이것이 동작을 보존하기를 바란다'를 구분하게 해줍니다.
    • 커버리지가 낮은 코드에 대한 HIGH/MEDIUM/LOW 임계값과 특성화 테스트 레시피는 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줄을 목표로 하세요: 한 번에 검토할 수 있을 만큼 작지만, 하나의 일관된 변경으로 읽힐 만큼 큽니다.
  • LLM 수동 편집보다 gopls Rename/Inline을 선호하세요.
    • 둘 다 구성에 의해 동작 보존됩니다 — Rename은 섀도잉, 인터페이스 충족 위반 또는 잘못된 코드가 있으면 잘못된 diff를 생성하는 대신 거부합니다; Inline은 부작용이 있는 인수를 복제하지 않고 var 임시 변수에 대체합니다.
    • 수십 개의 호출 사이트에 걸친 수동 편집은 이러한 보장이 없으며 측정 가능하게 사례를 놓칩니다.
  • 변경이 여러 사이트에서 반복되는 경우, 각 사이트를 수동 편집하는 대신 다시 쓰기 도구를 생성하세요.
    • gofmt -r → eg → gopatch → go/analysis fixer 순서대로, 증가하는 힘에 따라 단계를 올리세요 (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.

관련 스킬