К основному содержанию
скилл CX Codex

go-code-review · eduardo-sl — скилл для Claude Code: проверка Go-кода

Скилл проверяет Go-код и PR по структурированному списку: от обработки ошибок до тестов. Запускайте его перед слиянием изменений или для ревью пакета.

Установить в Claude Code · Через Skills CLI (Vercel) Все способы и платформы ↓
npx skills add eduardo-sl/go-agent-skills --skill go-code-review -a claude-code
Открыть на GitHub

Что делает go-code-review

Скилл проверяет изменения в Go-проекте: корректность, обработку ошибок, безопасность указателей и конкурентного кода, API, идиомы языка, структуру пакетов, тесты, документацию и зависимости. Можно ревьюить diff, выбранные файлы или пакеты, либо весь проект; для крупных кодовых баз процесс разбивается на отдельные проходы по темам.

Сначала скилл предлагает запустить go build ./..., go vet ./..., golangci-lint run и go test -race ./...; затем формирует отчёт с находками, уровнем серьёзности и ссылками на файл и строку. Скилл работает только на чтение и не исправляет код. Для работы нужен Go toolchain, а если его нет, соответствующий инструмент пропускается и отмечается в отчёте.

Какие задачи решает

  • проверить diff Go-проекта перед слиянием
  • найти ошибки обработки ошибок и nil-указателей
  • оценить структуру API и пакетов
  • проверить тесты и документацию Go-кода
  • собрать ревью всего Go-проекта по отдельным темам

Примеры запросов агенту

  • Проведи ревью этого diff перед слиянием.
  • Проверь файлы handler.go и связанные с ними тесты.
  • Сделай ревью всего Go-проекта и сгруппируй находки по серьёзности.

Как установить go-code-review

1Через Skills CLI (Vercel)

npx skills add eduardo-sl/go-agent-skills --skill go-code-review -a claude-code

2Вручную: положить файлы

~/.claude/skills/go-code-review/SKILL.md

Папка скилла целиком; для одного проекта — .claude/skills/go-code-review/

По шагам, с командами для каждой платформы: Как установить скилл в Claude Code: пять способов

Вопросы о go-code-review

Как установить go-code-review в Claude Code?

Выполните npx skills add eduardo-sl/go-agent-skills --skill go-code-review -a claude-code. Файл скилла находится по пути ~/.claude/skills/go-code-review/SKILL.md.

Что делает go-code-review?

Проверяет Go-код по категориям: корректность, идиомы, API, пакеты, тесты, документация и зависимости. Выдаёт находки с уровнем серьёзности и привязкой к строкам.

Нужен ли Go toolchain для go-code-review?

Да. Скилл использует Go toolchain и доступные инструменты вроде go vet и go test; отсутствующий инструмент пропускает и отмечает в отчёте.

Исходный текст

SKILL.md · MIT
---
name: go-code-review
description: >
  Comprehensive code review checklist for Go projects. Evaluates code
  quality, idiomatic patterns, error handling, naming, package structure,
  and test coverage. Use when reviewing Go code, PRs, or before merging
  changes. Trigger examples: "review this code", "check this PR", "code
  review", "review Go file".
  Not for: security audits (go-security-audit), performance analysis
  (go-performance-review).
user-invocable: true
license: MIT
compatibility: Designed for Claude Code or similar AI coding agents working on Go projects. Requires the Go toolchain. Read-only: this skill reports findings, it does not edit code.
allowed-tools: Read Glob Grep Bash(go:*) Bash(gofmt:*) Bash(golangci-lint:*)
metadata:
  author: eduardo-sl
  version: "1.4.0"
---

# Go Code Review

Structured code review process for Go. Reviews should be constructive, specific,
and cite the relevant principle behind each finding.

## Operating Modes

Pick the mode that matches the request before starting:

- **Diff review** (default) — review only the changed lines plus enough
  surrounding context to judge them. Use for PRs and working-tree changes.
- **File/package review** — review the named files or packages in full,
  including their tests.
- **Full audit** — sweep the entire codebase. Use the strategy in
  "Auditing Large Codebases" below and aggregate everything into one report.

## Review Process

Execute these steps in order. For each finding, classify severity:
- 🔴 **BLOCKER** — Must fix before merge. Correctness, data loss, security.
- 🟡 **WARNING** — Should fix. Maintainability, idiomatic Go, clarity.
- 🟢 **SUGGESTION** — Consider improving. Style, naming, documentation.

## 0. Run the Toolchain First

Before reading code manually, let the tools catch the mechanical issues
(skip any tool that is not installed and note it in the report):

```bash
go build ./...          # it must compile
go vet ./...            # suspicious constructs
golangci-lint run       # if the repo has a config
go test -race ./...     # tests pass, no data races
```

Report tool findings alongside manual findings — a failing `go vet` is
an automatic 🔴 BLOCKER. Never report an issue a tool already proves
absent.

## Verify Before Reporting

A finding that is wrong costs the author time and the reviewer trust.
Before writing one up:

- **Follow the diff outward.** Read the callers of a changed function and
  the callees it now relies on (the go-semantic-tools skill finds them by
  type, not by name). A bug can live outside the diff yet be triggered by
  it — and a "bug" inside it can be unreachable because a caller already
  guarantees the precondition.
- **Lower severity for upstream guarantees, don't drop the finding.** A
  nil dereference behind a constructor that never returns nil is a
  🟢 SUGGESTION to make that contract explicit, not a 🔴 BLOCKER.
- **Ask when intent is unclear** rather than asserting a bug — "is
  `retries` meant to include the first attempt?" beats a wrong fix.
- **Propose a check, not just an opinion.** Where a linter, a vet analyzer
  or a test could catch the issue next time, name it.

## 1. Correctness & Safety

### Error Handling
- Every error is checked. No blank identifier `_` discarding errors silently.
- Errors are wrapped with context: `fmt.Errorf("fetch user %d: %w", id, err)`.
- Error values compared with `errors.Is()` / `errors.As()`, never `==`.
- No `panic` outside of `init()` or truly unrecoverable situations.
- Errors handled exactly once — no log-and-return patterns.

### Nil Safety
- Pointer receivers checked before dereference when nil is a valid state.
- Map reads guarded or use comma-ok idiom.
- Channel operations consider closed/nil channels.
- Slice operations check bounds where relevant.

### Concurrency
- Shared mutable state protected by `sync.Mutex` or channels.
- No goroutine leaks — every goroutine has a clear termination path.
- Context propagation: all blocking calls accept and respect `context.Context`.
- `sync.WaitGroup` or `errgroup.Group` used for goroutine lifecycle.

## 2. API Design

- Exported functions have doc comments starting with the function name.
- Accept interfaces, return concrete types.
- Use functional options (`WithTimeout(d)`) over config structs for optional params.
- Context is always the first parameter: `func Foo(ctx context.Context, ...)`.
- Return `error` as the last return value.
- Avoid `bool` parameters — prefer named types or options.

## 3. Idiomatic Go

- Uses `:=` for local variables, `var` for zero-value intent.
- No unnecessary `else` after return/continue/break.
- Guard clauses and early returns reduce nesting.
- `defer` used for cleanup, placed right after resource acquisition.
- `range` used over manual index iteration where appropriate.
- Struct literals use field names.
- Interfaces defined at consumer, not producer.

## 4. Package Structure

- Package names are short, lowercase, singular nouns.
- No circular dependencies between packages.
- `internal/` used for non-public packages.
- `cmd/` contains main packages, one per binary.
- Clear separation of concerns — no god packages.

## 5. Testing

- Test functions follow `TestXxx` naming convention.
- Table-driven tests used for multiple input/output combinations.
- Test helpers use `t.Helper()` for clean stack traces.
- No test logic in `init()` — use `TestMain` when needed.
- Tests use `testify/assert` or `testify/require` consistently, or stdlib only.
- Edge cases covered: empty input, nil, zero values, max values.
- `t.Parallel()` used where safe.

## 6. Documentation

- All exported types, functions, and constants have doc comments.
- Doc comments start with the name of the entity.
- Package-level doc comment in `doc.go` for non-trivial packages.
- Complex algorithms or business logic have inline comments explaining *why*.

## 7. Dependencies

- `go.mod` has no replace directives in committed code (except monorepos).
- No unused dependencies.
- Dependencies are from well-maintained, reputable sources.
- Indirect dependencies are understood and acceptable.

## Auditing Large Codebases

When the scope exceeds ~20 files, do not read everything in one linear
pass. Split the audit into independent passes:

1. Enumerate packages (`go list ./...`) and group them by layer
   (handlers, services, stores, shared libraries).
2. Run one focused pass per concern from sections 1-7 (correctness,
   API design, idioms, structure, testing, docs, dependencies).
3. If your environment supports delegating work to parallel sub-agents
   or tasks, assign each pass to one — they are independent by design.
   Otherwise run them sequentially, one concern at a time.
4. Require every finding to cite `file.go:line` and severity so the
   final aggregation is mechanical: merge, deduplicate, sort by severity.

## Review Output Format

```text
## Code Review Summary

**Files reviewed:** <list>
**Overall assessment:** APPROVE | REQUEST CHANGES | COMMENT

### Findings

#### 🔴 BLOCKER: <title>
- **File:** `path/to/file.go:42`
- **Issue:** <what is wrong>
- **Why:** <which principle or guideline>
- **Fix:** <concrete suggestion>

#### 🟡 WARNING: <title>
...

#### 🟢 SUGGESTION: <title>
...

### What's Done Well
<genuine positive observations — always include at least one>
```

© eduardo-sl · MIT · eduardo-sl/go-agent-skills

Похожие скиллы

Все скиллы по теме «Код-ревью и рефакторинг» →

Сначала — go-code-review от других авторов.

go-code-review cxuu Проверяет Go-код по общепринятым стандартам стиля и выдаёт замечания по severity. Пригодится перед отправкой PR. CX Codex +1 1 700установок improve-codebase-architecture Matt Pocock Скилл ищет архитектурные узкие места в кодовой базе и показывает варианты углубления модулей в HTML-отчёте. Подойдёт для ревью перед рефакторингом. 1 163 035установок tdd Matt Pocock Скилл управляет циклом красный-зелёный в TDD: проверяет, что тесты пишутся до кода, держит их на уровне публичных интерфейсов и не завязывает на внутреннюю структуру. 1 141 062установок triage Matt Pocock Скилл проводит issue и внешние PR через роли триажа, проверку и подготовку брифа для агента. Подойдёт мейнтейнеру, который разбирает очередь задач. 990 453установок codebase-design Matt Pocock Скилл помогает проектировать модули с небольшим интерфейсом и скрытой внутри сложностью. Подходит для рефакторинга, тестируемости и поиска чистого seam. 850 344установок code-review Matt Pocock Проверяет изменения от выбранной точки по стандартам репозитория и требованиям задачи. Нужен для ревью ветки, PR или незавершённой работы. 789 521установок implement Matt Pocock Выполняет задачу по спецификации или тикетам, ведёт работу через тесты и завершает её ревью с коммитом. Подходит для задач, где нужен дисциплинированный цикл разработки. 774 700установок

Из того же набора22

go-modernize Скилл помогает применять современные возможности Go и стандартной библиотеки. Пригодится для точечных правок или модернизации пакета и модуля. CX Codex +1 ★ 83звёзд репо go-error-handling Скилл задаёт агенту правила работы с ошибками в Go: обёртка через %w, sentinel-ошибки, свои типы и errors.Is/errors.As. CX Codex +1 ★ 83звёзд репо go-data-structures Скилл помогает выбирать и безопасно использовать слайсы, карты и массивы в Go. Пригодится, когда нужно разобраться с append, nil-слайсами или порядком обхода карты. CX Codex +1 ★ 83звёзд репо go-context Скилл для ИИ-агента, который проверяет и правит работу с context.Context в Go: отмена, таймауты, значения, типичные ошибки. CX Codex +1 ★ 83звёзд репо go-project-layout Подсказывает, как разложить новый Go-проект по папкам: cmd/, internal/, плоская раскладка для мелких утилит. Пригодится в самом начале, когда структура ещё не сложилась. CX Codex +1 ★ 83звёзд репо go-interface-design Скилл помогает проектировать интерфейсы Go, разделять зависимости и проверять контракты на этапе компиляции. Пригодится при рефакторинге и подготовке к тестированию. CX Codex +1 ★ 83звёзд репо go-grpc Скилл для ИИ-агента, который ведёт разработку gRPC-сервисов на Go: proto-контракты, коды ошибок, дедлайны, интерцепторы и стриминг. CX Codex +1 ★ 83звёзд репо go-design-patterns Скилл помогает выбрать идиоматичный паттерн Go для создания объектов, смены поведения и обработки сбоев. Пригодится, когда нужно решить, как структурировать код. CX Codex +1 ★ 83звёзд репо

Спонсоры проекта

Компании, которые помогают держать аналитику открытой