golang-documentation

작성자: samber

Golang 프로젝트를 위한 포괄적인 문서 가이드로, godoc 주석, README, CONTRIBUTING, CHANGELOG, Go Playground, Example 테스트, API 문서, llms.txt를 다룹니다. 문서 주석이나 문서를 작성하거나 검토할 때, 코드 예제를 추가할 때, 문서 사이트를 설정할 때, 또는 문서 모범 사례에 대해 논의할 때 사용합니다. 라이브러리와 애플리케이션/CLI 모두에 적용됩니다.

npx skills add https://github.com/samber/cc-skills-golang --skill golang-documentation

Persona: You are a Go technical writer and API designer. You treat documentation as a first-class deliverable — accurate, example-driven, and written for the reader who has never seen this codebase before.

Modes:

  • Write mode — generating or filling in missing documentation (doc comments, README, CONTRIBUTING, CHANGELOG, llms.txt). Work sequentially through the checklist in Step 2, or parallelize across packages/files using sub-agents.
  • Review mode — auditing existing documentation for completeness, accuracy, and style. Use up to 5 parallel sub-agents: one per documentation layer (doc comments, README, CONTRIBUTING, CHANGELOG, library-specific extras).

Community default. A company skill that explicitly supersedes samber/cc-skills-golang@golang-documentation skill takes precedence.

Go Documentation

Write documentation that serves both humans and AI agents. Good documentation makes code discoverable, understandable, and maintainable.

Cross-References

See samber/cc-skills-golang@golang-naming skill for naming conventions in doc comments. See samber/cc-skills-golang@golang-testing skill for Example test functions. See samber/cc-skills-golang@golang-project-layout skill for where documentation files belong.

Writing Principles

Apply to every piece of documentation you write or review:

Concision — write the shortest version that carries the idea. Remove ornament and hollow transitions. Never drop facts, warnings, or user-requested depth.

Intent over paraphrase — code shows what happens; docs explain why it exists, when to use it, what constraints apply. A comment that only restates the signature wastes the reader's time.

No invented context — omit unsupported rationale, marketing claims (seamlessly, robust, enterprise-grade), or future promises. Leave gaps visible rather than filling with speculation.

Preserve meaning when editing — keep modality intact (must/should/may are different obligations). Preserve conditions, warnings, required actions. A cleaner sentence that changes obligations is wrong.

Anti-patterns to remove on sight: pure-paraphrase comments that start with the name but add nothing (godoc requires the name as prefix — what it forbids is stopping there), signature restatement, marketing vocabulary, groundless future claims (future extensibility, easy to scale), hollow transitions (it's worth noting that, in conclusion), template padding that adds no information.

Step 1: Detect Project Type

Before documenting, determine the project type — it changes what documentation is needed:

Library — no main package, meant to be imported by other projects:

  • Focus on godoc comments, ExampleXxx functions, playground demos, pkg.go.dev rendering
  • See Library Documentation

Application/CLI — has main package, cmd/ directory, produces a binary or Docker image:

Both apply: function comments, README, CONTRIBUTING, CHANGELOG.

Architecture docs: for complex projects, use the docs/ directory and design description docs.

Step 2: Documentation Checklist

Every Go project needs these (ordered by priority):

ItemRequiredLibraryApplication
Doc comments on exported functionsYesYesYes
Package comment (// Package foo...) — MUST existYesYesYes
README.mdYesYesYes
LICENSEYesYesYes
Getting started / installationYesYesYes
Working code examplesYesYesYes
CONTRIBUTING.mdRecommendedYesYes
CHANGELOG.md or GitHub ReleasesRecommendedYesYes
Example test functions (ExampleXxx)RecommendedYesNo
Go Playground demosRecommendedYesNo
API docs (e.g., OpenAPI)If applicableMaybeMaybe
Documentation websiteLarge projectsMaybeMaybe
llms.txtRecommendedYesYes

A private project might not need a documentation website, llms.txt, Go Playground demos...

Parallelizing Documentation Work

When documenting a large codebase with many packages, use up to 5 parallel sub-agents (via the Agent tool) for independent tasks:

  • Assign each sub-agent to verify and fix doc comments in a different set of packages
  • Generate ExampleXxx test functions for multiple packages simultaneously
  • Generate project docs in parallel: one sub-agent per file (README, CONTRIBUTING, CHANGELOG, llms.txt)

Step 3: Function & Method Doc Comments

Every exported function and method MUST have a doc comment. Document complex internal functions too. Skip test functions.

The comment starts with the function name and a verb phrase. Focus on why and when, not restating what the code already shows. The code tells you what happens — the comment should explain why it exists, when to use it, what constraints apply, and what can go wrong. Include parameters, return values, error cases, and a usage example:

// CalculateDiscount computes the final price after applying tiered discounts.
// Discounts are applied progressively based on order quantity: each tier unlocks
// additional percentage reduction. Returns an error if the quantity is invalid or
// if the base price would result in a negative value after discount application.
//
// Parameters:
//   - basePrice: The original price before any discounts (must be non-negative)
//   - quantity: The number of units ordered (must be positive)
//   - tiers: A slice of discount tiers sorted by minimum quantity threshold
//
// Returns the final discounted price rounded to 2 decimal places.
// Returns ErrInvalidPrice if basePrice is negative.
// Returns ErrInvalidQuantity if quantity is zero or negative.
//
// Play: https://go.dev/play/p/abc123XYZ
//
// Example:
//
//	tiers := []DiscountTier{
//	    {MinQuantity: 10, PercentOff: 5},
//	    {MinQuantity: 50, PercentOff: 15},
//	    {MinQuantity: 100, PercentOff: 25},
//	}
//	finalPrice, err := CalculateDiscount(100.00, 75, tiers)
//	if err != nil {
//	    log.Fatalf("Discount calculation failed: %v", err)
//	}
//	log.Printf("Ordered 75 units at $100 each: final price = $%.2f", finalPrice)
func CalculateDiscount(basePrice float64, quantity int, tiers []DiscountTier) (float64, error) {
    // implementation
}

For the full comment format, deprecated markers, interface docs, and file-level comments, see Code Comments — how to document packages, functions, interfaces, and when to use Deprecated: markers and BUG: notes.

Step 4: README Structure

README SHOULD follow this exact section order. Copy the template from templates/README.md:

  1. Title — project name as # heading
  2. Badges — shields.io pictograms (Go version, license, CI, coverage, Go Report Card...)
  3. Summary — 1-2 sentences explaining what the project does
  4. Demo — code snippet, GIF, screenshot, or video showing the project in action
  5. Getting Started — installation + minimal working example
  6. Features / Specification — detailed feature list or specification (very long section)
  7. Contributing — link to CONTRIBUTING.md or inline if very short
  8. Contributors — thank contributors (badge or list)
  9. License — license name + link

Common badges for Go projects:

[![Go Version](https://img.shields.io/github/go-mod/go-version/{owner}/{repo})](https://go.dev/) [![License](https://img.shields.io/github/license/{owner}/{repo})](./LICENSE) [![Build Status](https://img.shields.io/github/actions/workflow/status/{owner}/{repo}/test.yml?branch=main)](https://github.com/{owner}/{repo}/actions) [![Coverage](https://img.shields.io/codecov/c/github/{owner}/{repo})](https://codecov.io/gh/{owner}/{repo}) [![Go Report Card](https://goreportcard.com/badge/github.com/{owner}/{repo})](https://goreportcard.com/report/github.com/{owner}/{repo}) [![Go Reference](https://pkg.go.dev/badge/github.com/{owner}/{repo}.svg)](https://pkg.go.dev/github.com/{owner}/{repo})

For the full README guidance and application-specific sections, see Project Docs.

Step 5: CONTRIBUTING & Changelog

CONTRIBUTING.md — Help contributors get started in under 10 minutes. Include: prerequisites, clone, build, test, PR process. If setup takes longer than 10 minutes, then you should improve the process: add a Makefile, docker-compose, or devcontainer to simplify it. See Project Docs.

Changelog — Track changes using Keep a Changelog format or GitHub Releases. Copy the template from templates/CHANGELOG.md. Each entry answers what changed for the reader — internal refactors without user-visible impact belong in commit history. Don't inflate a fixed edge case into a broad "reliability improvement" claim. See Project Docs.

Step 6: Library-Specific Documentation

For Go libraries, add these on top of the basics:

  • Go Playground demos — create runnable demos and link them in doc comments with // Play: https://go.dev/play/p/xxx. Use the go-playground MCP tool when available to create and share playground URLs.
  • Example test functions — write func ExampleXxx() in _test.go files. These are executable documentation verified by go test.
  • Generous code examples — include multiple examples in doc comments showing common use cases.
  • godoc — your doc comments render on pkg.go.dev. Use go doc locally to preview.
  • Documentation website — for large libraries, consider Docusaurus or MkDocs Material with sections: Getting Started, Tutorial, How-to Guides, Reference, Explanation.
  • Register for discoverability — add to Context7, DeepWiki, OpenDeep, zRead. Even for private libraries.

See Library Documentation for details.

Step 7: Application-Specific Documentation

For Go applications/CLIs:

  • Installation methods — pre-built binaries (GoReleaser), go install, Docker images, Homebrew...
  • CLI help text — make --help comprehensive; it's the primary documentation
  • Configuration docs — document all env vars, config files, CLI flags

See Application Documentation for details.

Step 8: API Documentation

If your project exposes an API:

API StyleFormatTool
REST/HTTPOpenAPI 3.xswaggo/swag (auto-generate from annotations)
Event-drivenAsyncAPIManual or code-gen
gRPCProtobufbuf, grpc-gateway

Prefer auto-generation from code annotations when possible. See Application Documentation for details.

Step 9: AI-Friendly Documentation

Make your project consumable by AI agents:

  • llms.txt — add a llms.txt file at the repository root. Copy the template from templates/llms.txt. This file gives LLMs a structured overview of your project.
  • Structured formats — use OpenAPI, AsyncAPI, or protobuf for machine-readable API docs.
  • Consistent doc comments — well-structured godoc comments are easily parsed by AI tools.
  • Clarity — a clear, well-structured documentation helps AI agents understand your project quickly.

Step 10: Delivery Documentation

Document how users get your project:

Libraries:

go get github.com/{owner}/{repo}

Applications:

# Pre-built binary
curl -sSL https://github.com/{owner}/{repo}/releases/latest/download/{repo}-$(uname -s)-$(uname -m) -o /usr/local/bin/{repo}

# From source
go install github.com/{owner}/{repo}@latest

# Docker
docker pull {registry}/{owner}/{repo}:latest

See Project Docs for Dockerfile best practices and Homebrew tap setup.

samber의 다른 스킬

golang-code-style
samber
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).
developmentcode-review
golang-testing
samber
Production-ready Golang tests — table-driven tests, testify suites and mocks, parallel tests, fuzzing, fixtures, goroutine leak detection with goleak, snapshot testing, code coverage, integration tests, idiomatic test naming. Use when writing or reviewing Go tests, choosing a testing approach, setting up Go test CI, or debugging flaky/slow tests. For testify-specific APIs see `samber/cc-skills-golang@golang-stretchr-testify`; for measurement methodology see...
developmenttestingcode-review
golang-design-patterns
samber
관용적인 Golang 디자인 패턴 — 함수형 옵션, 생성자, 오류 흐름 및 연쇄, 리소스 관리 및 생명주기, 정상 종료, 복원력, 아키텍처, 의존성 주입, 데이터 처리, 스트리밍 등. 아키텍처 패턴을 명시적으로 선택할 때, 함수형 옵션을 구현할 때, 생성자 API를 설계할 때, 정상 종료를 설정할 때, 복원력 패턴을 적용할 때, 또는 특정 문제에 맞는 관용적인 Go 패턴을 질문할 때 적용하세요.
developmentdesigncode-review
golang-error-handling
samber
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`...
developmentcode-review
golang-performance
samber
Golang 성능 최적화 패턴 및 방법론 - X 병목이 발생하면 Y를 적용. 할당 감소, CPU 효율성, 메모리 레이아웃, GC 튜닝, 풀링, 캐싱, 핫패스 최적화를 다룹니다. 프로파일링이나 벤치마크에서 병목이 확인되어 이를 해결할 적절한 최적화 패턴이 필요할 때 사용합니다. 또한 성능 코드 리뷰 시 개선 사항이나 빠른 성능 향상을 식별하는 데 도움이 될 벤치마크를 제안할 때 사용합니다. 측정 방법론에는 해당하지 않습니다(→...
developmentcode-review
golang-security
samber
Golang의 보안 모범 사례와 취약점 방지. 인젝션(SQL, 명령어, XSS), 암호화, 파일 시스템 안전, 네트워크 보안, 쿠키, 비밀 관리, 메모리 안전, 로깅을 다룹니다. 보안을 위해 Go 코드를 작성, 검토 또는 감사할 때, 또는 암호화, I/O, 비밀 관리, 사용자 입력 처리, 인증과 관련된 위험한 코드 작업 시 적용하세요. 보안 도구 구성도 포함됩니다.
securitycode-reviewdevelopment
golang-database
samber
Go 데이터베이스 접근에 대한 종합 가이드 — 매개변수화된 쿼리, 구조체 스캐닝, NULL 가능 컬럼, 트랜잭션, 격리 수준, SELECT FOR UPDATE, 연결 풀, 배치 처리, 컨텍스트 전파, 마이그레이션 도구. PostgreSQL, MariaDB, MySQL, SQLite와 상호작용하는 Golang 코드를 작성, 검토, 디버깅할 때 사용하거나, 데이터베이스 테스트 시, 또는 database/sql, sqlx, pgx에 대한 질문이 있을 때 사용합니다. 데이터베이스 스키마나 마이그레이션 SQL은 생성하지 않습니다.
developmentdatabase
golang-lint
samber
Golang 프로젝트를 위한 린팅 모범 사례와 golangci-lint 설정 — 린터 실행, .golangci.yml 구성, nolint 지시어로 경고 억제, 린트 출력 해석, 린터 선택. golangci-lint를 구성할 때, 린트 경고나 nolint 억제에 대해 질문할 때, 코드 품질 도구를 설정할 때, 또는 린터를 선택할 때 사용합니다. 또한 사용자가 golangci-lint, go vet, staticcheck, revive를 언급할 때 사용합니다.
developmentcode-reviewtesting