К основному содержанию
скилл Claude Code CX Codex Cursor GitHub Copilot

golang-gopls — скилл для Claude Code: семантический анализ Go

Семантическая навигация и рефакторинг Go-кода через gopls, официальный языковой сервер. Пригодится, когда grep находит текст, а нужно понять типы, связи и структуру сборки.

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

Что делает golang-gopls

Скилл подключает агента к gopls — языковому серверу Go. Он отвечает на вопросы о вашей конкретной сборке: рабочее пространство и зависимости ровно в том виде, как они закреплены в go.sum, включая replace-директивы. Переход к определению, поиск использований, иерархия вызовов, поиск символа по workspace, API пакета, диагностика, безопасное переименование и рефакторинги вроде extract/inline — всё это через gopls.

Есть три пути к gopls, они не взаимозаменяемы. Собственный MCP-сервер (gopls mcp) заточен под агентов: инструменты принимают имена и пути вместо позиций курсора. Регистрируется один раз на машину: claude mcp add gopls -- gopls mcp. Нативный LSP-инструмент Claude Code требует ENABLE_LSP_TOOL=1 и плагин gopls-lsp@claude-plugins-official, зато автоматически подкидывает диагностику компилятора после каждой правки. CLI — экспериментальный и для отладки.

Для работы нужен бинарник gopls v0.20+ в PATH: go install golang.org/x/tools/gopls@latest. Скилл ограничен вашим локальным билдом — если нужно узнать про пакет, которого ещё нет в go.mod (версии, лицензии, импортёры), это к samber/cc-skills-golang@golang-pkg-go-dev. Аудит уязвимостей по всему дереву — к golang-security.

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

  • перейти к определению функции или типа
  • найти все места вызова перед переименованием
  • понять, что тянет файл из своего пакета
  • получить диагностику компилятора после правки
  • выполнить безопасный рефакторинг без поломки интерфейсов

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

  • найди определение этого типа в проекте
  • покажи все вызовы функции parseConfig перед тем как переименовать
  • какие ошибки компиляции сейчас в пакете handlers

Как установить golang-gopls

1Через Skills CLI (Vercel)

npx skills add samber/cc-skills-golang --skill golang-gopls -a claude-code

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

~/.claude/skills/golang-gopls/SKILL.md

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

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

Весь набор →
golang-code-style samber Скилл помогает писать понятный код на Go, разбирая правила длины строк, объявления переменных, управления потоком выполнения и комментариев. Пригодится при написании и ревью кода, обсуждении стилистики или установке стандартов проекта. Claude Code CX Codex Cursor +1 44 000установок golang-error-handling samber Скилл для идиоматичной обработки ошибок в Go: оборачивание с контекстом, проверка цепочек, структурированное логирование и интеграция с samber/oops. Применяется при создании, оборачивании, инспекции и логировании ошибок. Claude Code CX Codex Cursor +1 43 200установок golang-security samber Находит уязвимости в коде на Go, выстраивает аудит по STRIDE и DREAD и помогает закрывать инъекции, утечки секретов и ошибки в криптографии. Claude Code CX Codex Cursor +1 42 100установок golang-design-patterns samber Скилл подсказывает идиоматичные Go-паттерны для API, жизненного цикла ресурсов, graceful shutdown и архитектуры. Пригодится при проектировании и ревью кода. Claude Code CX Codex Cursor +1 41 900установок golang-performance samber Помогает находить и устранять узкие места в Go-коде: сокращает аллокации памяти, оптимизирует горячие циклы и проверяет результаты замеров. Claude Code CX Codex Cursor +1 41 800установок golang-concurrency samber Скилл задаёт правила для конкурентного кода на Go: жизненный цикл горутин, каналы и select, мьютексы, errgroup, singleflight, воркер-пулы и fan-out/fan-in пайплайны. Claude Code CX Codex Cursor +1 41 600установок golang-database samber Набор правил для работы с реляционными базами данных в Go через database/sql, sqlx и pgx. Помогает писать запросы без ORM и проверять утечки соединений. Claude Code CX Codex Cursor +1 40 700установок golang-naming samber Скилл задаёт правила имён в Go: пакеты, типы, ошибки, булевы поля и тесты. Пригодится при написании, ревью и рефакторинге кода. Claude Code CX Codex Cursor +1 40 700установок

Похожие

deep-agents-memory langchain-ai Скилл разбирает бэкенды памяти в Deep Agents: что живёт внутри одного потока, что переживает перезапуск и как включать файловые инструменты вроде ls и grep. Claude Code CX Codex Cursor +1 19 000установок cli-developer https://github.com/Jeffallan Скилл для разработки командной строки: помогает строить CLI-инструменты с парсингом флагов, интерактивными подсказками, прогресс-барами и автодополнением в bash/zsh/fish. Работает с commander, click, typer и cobra. Claude Code CX Codex Cursor +1 4 800установок opensrc vercel-labs Даёт агенту исходный код зависимостей, когда типов и документации мало для разбора внутренней логики или отладки поведения библиотеки. Claude Code CX Codex Cursor +1 2 600установок ralplan Yeachan-Heo Скилл запускает итеративное планирование с тремя агентами (планировщик, архитектор, критик) до согласования. Блокирует неясные задачи до утверждения, не переходит к исполнению без вашего одобрения. Claude Code CX Codex Cursor +1 1 200установок verified-agent-identity BillionsNetwork Скилл даёт агенту Ethereum-DID в сети Billions и учит проходить 402 Payment Required. Пригодится, когда нужно доказать, кто владелец агента, или оплатить доступ к API по x402. Claude Code CX Codex Cursor +1 8 200установок pretty-mermaid imxv Рендерит Mermaid-диаграммы в SVG, PNG или ASCII/Unicode без браузера. Пригодится для документации, README и терминалов. Claude Code CX Codex Cursor +1 4 500установок setup-matt-pocock-skills Matt Pocock Скилл настраивает репозиторий для инженерных скиллов Matt Pocock: задаёт трекер задач, метки триажа и расположение доменной документации. Запустите его перед первым использованием остальных скиллов. Claude Code 1 052 851установок to-tickets Matt Pocock Разбивает план, спецификацию или переписку на небольшие сквозные задачи и отмечает, какие из них блокируют остальные. Пригодится, когда нужно согласовать порядок работы до публикации задач в трекере. Claude Code 711 230установок

Вопросы о golang-gopls

Как установить golang-gopls в Claude Code?

Установите бинарник: go install golang.org/x/tools/gopls@latest (нужна версия 0.20+). Затем скилл: npx skills add samber/cc-skills-golang --skill golang-gopls -a claude-code. Файл попадёт в ~/.claude/skills/golang-gopls/SKILL.md.

Что делает golang-gopls?

Подключает агента к gopls — официальному языковому серверу Go. Даёт переход к определению, поиск использований, иерархию вызовов и реализаций, поиск символов, API пакетов, диагностику, безопасное переименование и рефакторинги.

Чем отличается от обычного grep по коду?

grep ищет текст, а gopls — смысл: типы, граф вызовов, затенение, отношения реализаций. Отвечает только о вашей локально разрешённой сборке из go.sum. Для пакетов вне go.mod нужен отдельный скилл godig.

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

SKILL.md · MIT
---
name: golang-gopls
description: "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`)."
user-invocable: true
license: MIT
compatibility: Designed for Claude Code, Codex or similar harness. Requires the gopls binary (go install golang.org/x/tools/gopls@latest) v0.20+ on PATH.
metadata:
  author: samber
  version: "1.1.1"
  openclaw:
    emoji: "🛰️"
    homepage: https://github.com/samber/cc-skills-golang
    requires:
      bins:
        - go
        - gopls
    install:
      - kind: go
        package: golang.org/x/tools/gopls@latest
        bins: [gopls]
    skill-library-version: "0.22.0"
allowed-tools: Read Edit Write Glob Grep Bash(go:*) Bash(golangci-lint:*) Bash(git:*) Agent Bash(gopls:*) LSP mcp__gopls__*
paths:
  - "**/*.go"
---

**Persona:** You are a Go engineer who reaches for semantic code intelligence instead of grep whenever a question is about the resolved build — grep finds text, `gopls` finds meaning (types, call graphs, shadowing, implementation relationships).

**Dependencies:** `gopls` — `go install golang.org/x/tools/gopls@latest` (v0.20+). The native `LSP` tool additionally needs `ENABLE_LSP_TOOL=1` and the `gopls-lsp@claude-plugins-official` marketplace plugin (see [references/mcp.md](references/mcp.md)).

`gopls` is the official Go language server. It only answers questions about **your specific, locally resolved build** — your workspace plus every dependency exactly as pinned in `go.sum`, including `replace` directives. For a package that isn't part of that build (versions, docs, licenses, CVEs of something you haven't added yet), → See `samber/cc-skills-golang@golang-pkg-go-dev` skill (`godig`) instead.

## Three ways to reach gopls

Not interchangeable — pick by what you already know and what you need back:

- **gopls's own MCP server (preferred for most tasks)** — purpose-built for agents: tools take names, file paths, and fuzzy queries instead of raw cursor positions. Register once per machine: `claude mcp add gopls -- gopls mcp`. Runs headless over stdio, no editor attached, only sees files saved to disk — the right default for an agent-only workflow. See [references/mcp.md](references/mcp.md) for every tool.
- **The native `LSP` tool** — Claude Code's built-in editor-style integration. Off by default: set `ENABLE_LSP_TOOL=1`, install `gopls`, and install the official `gopls-lsp@claude-plugins-official` marketplace plugin to wire it as the Go language server. Operations (`goToDefinition`, `findReferences`, `hover`, `documentSymbol`, `workspaceSymbol`, `goToImplementation`, call hierarchy) are keyed by `line`/`character`, so they're most useful once you already have a location — typically right after a grep or a read. Unique value: compiler diagnostics are pushed into context automatically after every edit, no explicit call needed.
- **The `gopls` CLI** — same engine, invoked as `gopls <command> <file:line:col>`. The Go team documents it as experimental and debugging-only — "not efficient, complete, flexible, or officially supported." Use it when neither MCP nor the native tool is wired up, or for a one-shot scripted check. Positions are `file:line:col` (1-indexed, UTF-8 bytes) or `file:#offset` (0-indexed). See [references/cli.md](references/cli.md).

**Preference order: MCP → native `LSP` → CLI.** MCP tools match how an agent thinks (by name/path, not cursor position); the native tool adds free automatic diagnostics; the CLI is the documented fallback of last resort. Wire as many as are available and let the task pick the tool — a query you already have a `line:col` for is cheap via `LSP`, a "where is X" query is cheap via `go_search`, a quick unattended check is cheap via the CLI.

## Capability → CLI → MCP → native LSP

Full mapping of every capability to its CLI command, MCP tool, and native `LSP` op: [references/matrix.md](references/matrix.md).

## Use cases

- **Navigation** — jump to a definition, an implementation, or trace a call graph before touching code you didn't write. Details: [references/features.md](references/features.md#navigation).
- **Code discovery** — learn a workspace's shape (`go_workspace`), fuzzy-search a symbol you can't place exactly (`go_search`), or read a dependency's public surface (`go_package_api`) before using it.
- **Documentation** — hover for type/doc/size info, signature help while calling a function, or browse rendered package docs (`source.doc`, including internal packages pkg.go.dev never sees).
- **Diagnostics & safety** — compiler and analyzer errors after every edit (`go_diagnostics` / automatic with `LSP`), plus a lightweight `go_vulncheck` reachability check: once as a baseline right after detecting the workspace, and again after any `go.mod` change.
- **Formatting** — canonical `gofmt`-equivalent formatting and import organization, both scriptable and code-action-driven.
- **Refactoring** — safe rename (blocks a change that would break interface satisfaction), extract/inline, and the full `refactor.rewrite.*` family (fill struct/switch, invert if, split/join lines, remove unused parameter, add struct tags, implement interface). Full catalog with gotchas: [references/features.md](references/features.md#transformation).

## Efficient workflows

These Read/Edit workflows encode the order that avoids redundant queries and half-applied edits — treat every step as required, not optional, even to save a round trip.

- **Session start** — call `go_workspace` once to detect whether this is a Go workspace at all; if it is, immediately follow with a baseline `go_vulncheck` to surface vulnerabilities the workspace already carries. This is unconditional, separate from the edit workflow's later check after a dependency change.

**Read workflow** (understand before touching anything):

1. `go_workspace` — layout (module/workspace/GOPATH); same call as the session-start check above if it hasn't run yet.
2. `go_search` — fuzzy-locate a type/function/variable by name.
3. `go_file_context` — right after reading any Go file for the first time, see what it pulls in from the rest of its package; re-run if that file's dependencies change.
4. `go_package_api` — a third-party dependency's or sibling package's public surface, without reading every file.

**Edit workflow** (iterate until diagnostics are clean):

1. Read first (workflow above).
2. `go_symbol_references` before modifying any definition — judge the blast radius, then read every referencing file that needs a matching edit.
3. Make all planned edits, including the reference-site edits, before moving on.
4. `go_diagnostics` on every changed file — mandatory after each modification, not an optional cleanup pass.
5. Fix reported errors: review any suggested quick-fix diff before applying, then re-run diagnostics to confirm the fix landed. Ignore hint/info diagnostics unrelated to the task. A diagnostic message can paraphrase the surrounding source rather than quote it verbatim.
6. Only if `go.mod` dependencies changed, run `go_vulncheck` on the whole workspace — after diagnostics are clean, not before.
7. Run `go test <changed-package-paths>` — not `./...` unless explicitly asked, since a full-repo run slows the iteration loop.

**Gotchas worth knowing before you rely on a result:**

- `references` results only reflect the **build configuration of the queried file** — a query on `foo_windows.go` will not surface matches in `bar_linux.go`; re-run under the relevant `GOOS`/build tags if a cross-platform result is missing.
- `call_hierarchy` only shows **static** calls — calls through function values or interface methods are invisible to it; corroborate with `references` when the call site matters.
- Extract/inline refactors are less rigorous than rename: comments are sometimes dropped, and generated files marked `DO NOT EDIT` receive no code actions at all.
- `refactor.rewrite.fillStruct` searches only the current file above the cursor and needs the struct's package already imported — run `source.organizeImports` first if the type was just typed in.

## gopls vs godig vs Context7 vs govulncheck

`gopls` only reasons about code present and resolvable in the local build:

- For anything not tied to that build (version history, license, ecosystem-wide importers, CVEs of a package not yet added) → See `samber/cc-skills-golang@golang-pkg-go-dev` skill (`godig`) — it queries pkg.go.dev directly, no local checkout needed.
- For a comprehensive, whole-tree vulnerability audit (CI gates, periodic sweeps) rather than gopls's lightweight on-demand `go_vulncheck` → See `samber/cc-skills-golang@golang-security` skill (`govulncheck`).
- Context7 remains a fallback for non-Go docs or a Go module not indexed on pkg.go.dev.

The full task-to-tool matrix lives in the `samber/cc-skills-golang@golang-how-to` skill's "`godig` vs gopls vs Context7 vs govulncheck" section.

© samber · MIT · samber/cc-skills-golang

Смотрите также

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

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