Golang Documentation
Samuel BertheCommunityCreated by samberDistributed by Samuel Berthe
- Skill
- Guidelines
- Software development
- MIT
- Low risk
AutoGineer summary
Written by AutoGineer from the skill’s own files, not by the author
This skill provides a structured framework for documenting Golang libraries and applications. It covers essential components such as godoc comments, README files, CONTRIBUTING guides, CHANGELOGs, and llms.txt. The guide emphasizes writing documentation that serves both human developers and AI agents, focusing on intent, concision, and clarity while avoiding common anti-patterns like signature restatement or marketing language.
What it does
- Provides templates and checklists for standard Go project documentation files.
- Defines best practices for writing godoc comments that explain intent and constraints.
- Offers guidance on structuring READMEs, CONTRIBUTING files, and CHANGELOGs.
- Supports the creation of machine-readable documentation like llms.txt and API specs.
- Facilitates the generation of executable documentation via Example test functions.
- Enables parallelized documentation auditing and generation across large codebases.
When to use it
- When initializing documentation for a new Go library or application.
- When auditing existing codebases for missing or unclear doc comments.
- When standardizing documentation across multiple Go packages.
- When preparing a project for better consumption by AI agents and developers.
- When adding new features that require updated API or usage documentation.
Advantages
- Ensures consistent documentation structure across Go projects.
- Improves code discoverability and maintainability through clear intent-based comments.
- Reduces technical debt by removing redundant or hollow documentation.
- Supports automation through machine-readable formats like llms.txt and OpenAPI.
- Promotes the use of executable examples to keep documentation accurate.
Usage examples
- “Audit the current package for missing doc comments and suggest improvements.”
- The agent reviews exported functions, identifies missing or purely paraphrased comments, and proposes updates that explain the 'why' and 'when' for each function.
- “Generate a standard README.md for this Go library.”
- The agent creates a README following the specified structure, including badges, installation instructions, and a minimal working example.
- “Create a llms.txt file for this repository.”
- The agent generates a structured llms.txt file that provides an overview of the project to assist AI agents in understanding the codebase.
- “Help me write a doc comment for a complex function.”
- The agent drafts a comment including parameters, return values, error conditions, and a usage example, following the Go documentation standards.
Install
Download the skill as a ZIP:
https://mp-staging.autogineer.com/agent-skills/samber/golang-documentation/downloadUnzip it into the cross-client skills folder of your project:
mkdir -p .agents/skills && unzip golang-documentation.zip -d .agents/skills
Documentation by samber
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.
Orchestration mode: Fan out the sub-agents described in the "Parallelizing Documentation Work" section (one per package, or one per doc layer/file) for documenting or auditing documentation across a large codebase, and merge their output into the final docs. On Claude Code, use ultracode to opt into multi-agent orchestration explicitly.
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-documentationskill 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-namingskill for naming conventions in doc comments.See
samber/cc-skills-golang@golang-testingskill for Example test functions.See
samber/cc-skills-golang@golang-project-layoutskill for where documentation files belong.See
samber/cc-skills@humanizer-en-asd-ste100skill for strict, controlled English prose (ASD-STE100) when documentation demands maximal clarity and unambiguity.
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.
For regulated or safety-critical documentation that requires strict controlled-English prose, → See samber/cc-skills@humanizer-en-asd-ste100 skill.
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,
ExampleXxxfunctions, playground demos, pkg.go.dev rendering
Application/CLI — has main package, cmd/ directory, produces a binary or Docker image:
Focus on installation instructions, CLI help text, configuration docs
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):
| Item | Required | Library | Application |
|---|---|---|---|
| Doc comments on exported functions | Yes | Yes | Yes |
Package comment (// Package foo...) — MUST exist | Yes | Yes | Yes |
| README.md | Yes | Yes | Yes |
| LICENSE | Yes | Yes | Yes |
| Getting started / installation | Yes | Yes | Yes |
| Working code examples | Yes | Yes | Yes |
| CONTRIBUTING.md | Recommended | Yes | Yes |
| CHANGELOG.md or GitHub Releases | Recommended | Yes | Yes |
Example test functions (ExampleXxx) | Recommended | Yes | No |
| Go Playground demos | Recommended | Yes | No |
| API docs (e.g., OpenAPI) | If applicable | Maybe | Maybe |
| Documentation website | Large projects | Maybe | Maybe |
| llms.txt | Recommended | Yes | Yes |
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 for independent tasks:
Assign each sub-agent to verify and fix doc comments in a different set of packages
Generate
ExampleXxxtest functions for multiple packages simultaneouslyGenerate 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:
Title — project name as
# headingBadges — shields.io pictograms (Go version, license, CI, coverage, Go Report Card...)
Summary — 1-2 sentences explaining what the project does
Demo — code snippet, GIF, screenshot, or video showing the project in action
Getting Started — installation + minimal working example
Features / Specification — detailed feature list or specification (very long section)
Contributing — link to CONTRIBUTING.md or inline if very short
Contributors — thank contributors (badge or list)
License — license name + link
Common badges for Go projects:
[](https://go.dev/) [](./LICENSE) [](https://github.com/{owner}/{repo}/actions) [](https://codecov.io/gh/{owner}/{repo}) [](https://goreportcard.com/report/github.com/{owner}/{repo}) [](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, covering prerequisites, clone, build, test, and PR process. If setup takes longer, improve the process with a Makefile, docker-compose, or devcontainer. See Project Docs.
Changelog — Track changes using Keep a Changelog format or GitHub Releases, copying the template from templates/CHANGELOG.md. Write each entry to answer what changed for the reader — internal refactors without user-visible impact belong in commit history, and a fixed edge case never becomes 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 a Go Playground integration when one is available to create and share playground URLs.Example test functions — write
func ExampleXxx()in_test.gofiles. These are executable documentation verified bygo 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 doclocally to preview; to inspect how a published package renders its docs, symbols, and examples, → Seesamber/cc-skills-golang@golang-pkg-go-devskill.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
--helpcomprehensive; it's the primary documentationConfiguration 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 Style | Format | Tool |
|---|---|---|
| REST/HTTP | OpenAPI 3.x | swaggo/swag (auto-generate from annotations) |
| Event-driven | AsyncAPI | Manual or code-gen |
| gRPC | Protobuf | buf, 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.txtfile 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}:latestSee Project Docs for Dockerfile best practices and Homebrew tap setup.
Files
- ATTRIBUTION.mdAdded by AutoGineer917 B
- LICENSELicence file added by AutoGineer1.0 KiB
- SKILL.md13.7 KiB
- assets/templates/CHANGELOG.md675 B
- assets/templates/CONTRIBUTING.md1.1 KiB
- assets/templates/README.md3.8 KiB
- assets/templates/llms.txt1.2 KiB
- evals/evals.json31.2 KiB
- references/application.md5.8 KiB
- references/code-comments.md12.0 KiB
- references/library.md7.3 KiB
- references/project-docs.md4.3 KiB
references/code-comments.md
Code Comments
→ See samber/cc-skills-golang@golang-naming skill for naming conventions that reduce the need for comments.
Table of Contents
Function & Method Doc Comments
Why, Not What
Anti-Patterns to Remove on Sight
Format
Full Comment Template
What to Document
Error Cases and Limitations
Deprecated Functions
Interface Documentation
Method Comments on Structs
Inline Code Examples in Comments
Playground Links
File & Package Comments
Package Comment
File-Level Description
When to Add File Descriptions
Godoc Headings in Comments
Function & Method Doc Comments
Why, Not What
The most common mistake in doc comments is restating the code. The code already tells the reader what happens — comments SHOULD explain why, not what:
Why this function exists (its purpose in the system)
When to use it (and when not to)
What constraints apply (preconditions, thread safety, performance)
What can go wrong (error cases, panics, edge cases)
Bad — restates the code:
// GetUser gets a user by ID.
func GetUser(id string) (*User, error) {Good — explains why, when, and what can go wrong:
// GetUser retrieves a user from the database by their unique identifier.
// Use this for authenticated endpoints where you need the full user profile.
// For listing or searching, use ListUsers instead — it returns lighter projections.
//
// Returns ErrNotFound if no user exists with the given ID.
// Returns ErrDatabaseUnavailable if the connection pool is exhausted.
func GetUser(id string) (*User, error) {Anti-Patterns to Remove on Sight
| Anti-pattern | Example | Fix |
|---|---|---|
| Pure paraphrase | // GetUser gets a user on func GetUser() — starts with the name (required by godoc) but adds nothing | After the name, add when to use it, constraints, and what can go wrong |
| Signature restatement | // Returns a string and an error | Document which error and why — the signature already shows types |
| Marketing vocabulary | seamlessly, powerful, robust, enterprise-grade | Remove — state facts instead |
| Invented rationale | // designed to improve scalability | Only document what the code actually does |
| Groundless future claims | // supports future extensibility | Remove or back it with an interface or configuration |
| Hollow filler | // It's worth noting that..., // As mentioned above | Cut — restate the fact directly if it matters |
Format
Every doc comment MUST start with the function/method name followed by a verb phrase. This is how godoc renders it in package indexes.
// FuncName verb-phrase describing what it does.Full Comment Template
Use this structure for exported functions and complex internal functions. Omit sections that don't apply (e.g., no Parameters section for zero-arg functions). Focus on the "why" — don't restate what the code already makes obvious:
// FuncName summarizes what this function does in one sentence.
// Additional context explaining behavior, algorithms, or design decisions
// that callers need to know.
//
// Parameters:
// - paramName: description of what this parameter represents
// - anotherParam: description with valid ranges or constraints
//
// Returns description of the return value(s).
// Returns ErrSomething if [condition].
// Returns ErrAnother if [different condition].
//
// Panics if [condition] (only document if the function can panic).
//
// It is safe for concurrent use (or: It is NOT safe for concurrent use).
//
// Play: https://go.dev/play/p/xxxxx
//
// Example:
//
// result, err := pkg.FuncName(arg1, arg2)
// if err != nil {
// log.Fatal(err)
// }
// fmt.Println(result)
func FuncName(paramName Type, anotherParam Type) (ResultType, error) {What to Document
| Element | Document? |
|---|---|
| Exported functions/methods | Always |
| Exported types and interfaces | Always |
| Exported constants and variables | Always |
| Complex internal functions | Yes — algorithms, non-obvious logic |
| Simple internal helpers | Optional — only if the name isn't self-explanatory |
| Test functions | No |
| Getters/setters with no logic | Brief one-liner is enough |
TODO comments SHOULD include a tracking issue reference when one exists (e.g., // TODO(#123): ...). For informal notes, // TODO(username): ... or plain // TODO: ... is acceptable.
Error Cases and Limitations
Document every error a function can return, and any edge cases or limitations:
// Parse parses a duration string such as "300ms", "1.5h", or "2h45m".
//
// Parameters:
// - s: A duration string. Valid time units are "ns", "us", "ms", "s", "m", "h".
//
// Returns the parsed duration.
// Returns ErrInvalidDuration if the string is empty or has an invalid format.
// Returns ErrOverflow if the duration exceeds math.MaxInt64 nanoseconds.
//
// Limitations:
// - Does not support day, week, month, or year units.
// - Precision is limited to nanoseconds.
func Parse(s string) (time.Duration, error) {Deprecated Functions
Use the Deprecated: marker. godoc renders this with special styling:
// OldFunc does something.
//
// Deprecated: Use NewFunc instead. OldFunc will be removed in v3.0.0.
func OldFunc() {}Interface Documentation
Document the interface itself and each method. Explain the contract that implementations must satisfy:
// Store defines a persistent key-value storage backend.
// Implementations must be safe for concurrent use by multiple goroutines.
//
// All methods accept a context for cancellation and deadlines.
// Implementations should respect context cancellation and return
// ctx.Err() when the context is done.
type Store interface {
// Get retrieves the value associated with key.
// Returns ErrNotFound if the key does not exist.
// Returns ErrExpired if the key exists but has expired.
Get(ctx context.Context, key string) ([]byte, error)
// Set stores a key-value pair with an optional TTL.
// If ttl is 0, the entry does not expire.
// Overwrites any existing value for the same key.
Set(ctx context.Context, key string, value []byte, ttl time.Duration) error
// Delete removes a key from the store.
// Returns nil (not an error) if the key does not exist.
Delete(ctx context.Context, key string) error
}Method Comments on Structs
// Close gracefully shuts down the server.
// It waits for active connections to complete up to the configured timeout.
//
// Returns an error if the shutdown times out or if the server
// encounters an error while draining connections.
//
// Close is idempotent — calling it multiple times is safe.
// It is NOT safe to call Close concurrently from multiple goroutines.
func (s *Server) Close() error {Inline Code Examples in Comments
Indent code examples by one tab in doc comments. godoc renders these as formatted code blocks:
// Transform applies a function to each element of a slice and returns
// a new slice with the results.
//
// Example:
//
// names := []string{"alice", "bob"}
// upper := Transform(names, strings.ToUpper)
// // upper: ["ALICE", "BOB"]
func Transform[T any, U any](slice []T, fn func(T) U) []U {Playground Links
Add a Play: line linking to a runnable Go Playground example of a public library. Use a Go Playground integration to create and share playground URLs when one is available:
// Map applies a function to each element of a slice.
//
// Play: https://go.dev/play/p/abc123xyz
//
// Example:
//
// doubled := Map([]int{1, 2, 3}, func(x int) int { return x * 2 })
// // doubled: [2, 4, 6]
func Map[T any, U any](s []T, fn func(T) U) []U {File & Package Comments
Package Comment
Every package should have a doc comment. Place it in one of these locations:
At the top of the main
.gofile — for small packages with one or two filesIn a dedicated
doc.gofile — for packages with many files
// Package httputil provides HTTP utility functions for request parsing,
// response writing, and middleware chaining.
//
// It is designed to work with the standard net/http package and does not
// depend on any specific HTTP framework.
package httputilUse doc.go when the package has 3+ files or the package comment is longer than ~10 lines:
// Package auth implements authentication and authorization for the API server.
//
// # Architecture
//
// The package uses a middleware-based approach where each authentication
// strategy (JWT, API key, OAuth2) implements the Authenticator interface.
// Strategies are chained and tried in order until one succeeds.
//
// # Token Lifecycle
//
// Access tokens expire after 15 minutes. Refresh tokens expire after 7 days.
// Token rotation is automatic — each refresh request issues a new refresh token
// and invalidates the previous one.
//
// # Thread Safety
//
// All exported functions and types are safe for concurrent use.
package authFile-Level Description
For files that implement a specific algorithm, feature, or contain complex logic, add a descriptive comment block below the imports. This is a macro description — explain why this file or package exists, what problem it solves, and what design choices were made. Use ASCII art to describe complex flows or architectures. Don't describe what each line does:
package scheduler
import (
"container/heap"
"sync"
"time"
)
// This file implements a priority-queue-based task scheduler.
//
// Tasks are scheduled with a target execution time and stored in a min-heap
// ordered by deadline. A single dispatcher goroutine polls the heap and
// executes tasks when their deadline arrives.
//
// Supports: recurring tasks, one-shot tasks, task cancellation, and
// graceful shutdown with drain timeout.
//
// Architecture:
//
// Schedule(task)
// |
// v
// [Min-Heap Queue]
// (by deadline)
// |
// Dispatcher Goroutine
// (polling loop)
// / \
// / \
// Deadline Deadline
// not reached reached
// | |
// wait v
// Execute
// |
// Recurring? | One-shot
// / | \
// / v \
// Re-queue Complete Discard
// \ | /
// \ | /
// v v v
// [Continue polling]
type Scheduler struct {When to Add File Descriptions
| Scenario | Add description? |
|---|---|
| File implements an algorithm (sorting, scheduling, tree traversal) | Yes |
| File contains a complex state machine or protocol | Yes |
| File has 200+ lines of related logic | Yes |
| File is a simple CRUD handler or data model | No |
File name already explains everything (json_parser.go) | Only if non-obvious |
Godoc Headings in Comments
Use # Heading syntax in doc comments (Go 1.19+) for structured documentation:
// Package config provides configuration loading and validation.
//
// # Supported Sources
//
// Configuration can be loaded from environment variables, YAML files,
// or command-line flags. Sources are merged in order of precedence:
// flags > env vars > config file > defaults.
//
// # Validation
//
// All configuration values are validated at load time. Invalid values
// cause an immediate error rather than failing later at runtime.
package configRequirements and compatibility
Written for: Claude Code, OpenAI Codex
Works with: Claude Code, Claude apps, OpenAI Codex, GitHub Copilot, Cursor, Gemini CLI, Kiro, OpenCode, Goose, Amp, Roo Code, JetBrains Junie, Factory Droid, Devin (ex-Windsurf), Mistral Vibe, OpenHands, Letta
“Works with” means the tool reads the open Agent Skills format; a skill written for one tool may use features others lack.
Needs: Declares allowed tools, Claude Code frontmatter, Needs network access, Needs a command-line tool
The author says: Designed for Claude Code, Codex or similar harness, and for projects using Golang.
Security
What our scanner noticed· Low risk
- Instructions that use the network
A static scan is not a guarantee. Skills are third-party content: review a skill before you let an agent use it.
Attribution and licence
- Created by
- samber
- Publisher
- Samuel Berthe (Community)
- Distributed by
- Samuel Berthe
- Source
- samber/cc-skills-golang · skills/golang-documentation · commit bb1d43d
- Licence
- MIT License (redistribution allowed)
- LICENSE (added by AutoGineer from LICENSE)
- ATTRIBUTION.md (written by AutoGineer)
- Synced
AutoGineer is not affiliated with or endorsed by samber or Samuel Berthe.
Download ZIP
The ZIP holds the skill’s files, its licence files and an ATTRIBUTION.md. Download golang-documentation.zip