# Golang Lint > Buenas prácticas de linting y configuración de golangci-lint para proyectos Golang: ejecutar linters, configurar .golangci.yml, suprimir avisos con nolint, interpretar salidas y elegir linters. Fuente: https://skillsagentes.com/skills/samber/cc-skills-golang/golang-lint Markdown: https://skillsagentes.com/skills/samber/cc-skills-golang/golang-lint.md Repositorio: https://github.com/samber/cc-skills-golang Autor: samber Licencia: MIT Actualizado: hace 4 días Coste de contexto: 109 tok instalada, 1.8k tok al activarse, 10.4k tok con todos los archivos del bundle Bundle: 5 archivos, 41 KB Permisos que pide: read edit write glob grep bash(go:*) bash(golangci-lint:*) bash(git:*) agent ## Instalación Un skill son archivos markdown: los mismos archivos valen para cualquier agente y lo único que cambia es el directorio de destino, es decir la bandera `--agent`. Añade `-g` para instalarlo en todos los proyectos de la máquina. ```bash # Claude Code npx -y skills add samber/cc-skills-golang --skill golang-lint --agent claude-code # Cursor npx -y skills add samber/cc-skills-golang --skill golang-lint --agent cursor # Codex npx -y skills add samber/cc-skills-golang --skill golang-lint --agent codex # Gemini CLI npx -y skills add samber/cc-skills-golang --skill golang-lint --agent gemini # Windsurf npx -y skills add samber/cc-skills-golang --skill golang-lint --agent windsurf # Cline npx -y skills add samber/cc-skills-golang --skill golang-lint --agent cline ``` ## Qué hace - Configura y ejecuta golangci-lint con un archivo .golangci.yml de referencia con hasta 48 linters - Explica cómo suprimir advertencias con directivas //nolint incluyendo linter y justificación - Interpreta la salida de los linters y ayuda a elegir qué linters activar - Orquesta hasta 5 sub-agentes en paralelo para limpiar código legacy por categorías de linters ## Cuándo usarla - Al configurar golangci-lint o el archivo .golangci.yml - Cuando surgen dudas sobre advertencias de lint o supresiones con nolint - Al configurar herramientas de calidad de código en el proyecto - Cuando el usuario menciona golangci-lint, go vet, staticcheck o revive ## Qué la activa - "Ayúdame a configurar el .golangci.yml de mi proyecto Go" - "¿Por qué golangci-lint marca este error y cómo lo suprimo?" - "Quiero limpiar los warnings de lint en un proyecto Go legacy" - "¿Qué linters debería activar para mi proyecto Go?" ## Antes de instalar - Requiere los binarios go y golangci-lint instalados (por ejemplo vía brew install golangci-lint). ## Archivos - SKILL.md — 7 KB - assets/.golangci.yml — 8 KB - evals/evals.json — 16 KB - references/linter-reference.md — 8 KB - references/nolint-directives.md — 2 KB ## SKILL.md Reproducido tal cual desde samber/cc-skills-golang bajo MIT. Esta sección es el documento original y está en inglés. **Persona:** You are a Go code quality engineer. You treat linting as a first-class part of the development workflow — not a post-hoc cleanup step. **Orchestration mode:** Use `ultracode` when adopting linting on a legacy codebase — orchestrate the five sub-agents described in the "Parallelizing Legacy Codebase Cleanup" section (auto-fix, security linters, error handling, style/formatting, code quality) so independent linter categories are fixed concurrently. **Modes:** - **Setup mode** — configuring `.golangci.yml`, choosing linters, enabling CI: follow the configuration and workflow sections sequentially. - **Coding mode** — writing new Go code: launch a background agent running `golangci-lint run --fix` on the modified files only while the main agent continues implementing the feature; surface results when it completes. - **Interpret/fix mode** — reading lint output, suppressing warnings, fixing issues on existing code: start from "Interpreting Output" and "Suppressing Lint Warnings"; use parallel sub-agents for large-scale legacy cleanup. **Dependencies:** - golangci-lint: `go install github.com/golangci/golangci-lint/cmd/golangci-lint@latest` # Go Linting ## Overview `golangci-lint` is the standard Go linting tool. It aggregates 100+ linters into a single binary, runs them in parallel, and provides a unified configuration format. Run it frequently during development and always in CI. Every Go project MUST have a `.golangci.yml` — it is the **source of truth** for which linters are enabled and how they are configured. See the [recommended configuration](./assets/.golangci.yml) for a production-ready setup with 48 linters enabled. ## Quick Reference ```bash # Run all configured linters golangci-lint run ./... # Auto-fix issues where possible golangci-lint run --fix ./... # Format code (golangci-lint v2+) golangci-lint fmt ./... # Run a single linter only golangci-lint run --enable-only govet ./... # List all available linters golangci-lint linters # Verbose output with timing info golangci-lint run --verbose ./... ``` ## Configuration The [recommended .golangci.yml](./assets/.golangci.yml) provides a production-ready setup with 33 linters. For configuration details, linter categories, and per-linter descriptions, see the **[linter reference](./references/linter-reference.md)** — which linters check for what (correctness, style, complexity, performance, security), descriptions of all 33+ linters, and when each one is useful. ## Suppressing Lint Warnings Use `//nolint` directives sparingly — fix the root cause first. ```go // Good: specific linter + justification //nolint:errcheck // fire-and-forget logging, error is not actionable _ = logger.Sync() // Bad: blanket suppression without reason //nolint _ = logger.Sync() ``` Rules: 1. **//nolint directives MUST specify the linter name**: `//nolint:errcheck` not `//nolint` 2. **//nolint directives MUST include a justification comment**: `//nolint:errcheck // reason` 3. **The `nolintlint` linter enforces both rules above** — it flags bare `//nolint` and missing reasons 4. **NEVER suppress security linters** (gosec, bodyclose, sqlclosecheck) without a very strong reason For comprehensive patterns and examples, see **[nolint directives](./references/nolint-directives.md)** — when to suppress, how to write justifications, patterns for per-line vs per-function suppression, and anti-patterns. ## Development Workflow 1. **Linters SHOULD be run after every significant change**: `golangci-lint run ./...` 2. **Auto-fix what you can**: `golangci-lint run --fix ./...` 3. **Format before committing**: `golangci-lint fmt ./...` 4. **Incremental adoption on legacy code**: set `issues.new-from-rev` in `.golangci.yml` to only lint new/changed code, then gradually clean up old code Makefile targets (recommended): ```makefile lint: golangci-lint run ./... lint-fix: golangci-lint run --fix ./... fmt: golangci-lint fmt ./... ``` For CI pipeline setup (GitHub Actions with `golangci-lint-action`), see the `samber/cc-skills-golang@golang-continuous-integration` skill. ## Interpreting Output Each issue follows this format: ``` path/to/file.go:42:10: message describing the issue (linter-name) ``` The linter name in parentheses tells you which linter flagged it. Use this to: - Look up the linter in the [reference](./references/linter-reference.md) to understand what it checks - Suppress with `//nolint:linter-name // reason` if it's a false positive - Use `golangci-lint run --verbose` for additional context and timing ## Common Issues | Problem | Solution | | --- | --- | | "deadline exceeded" | Set or increase `run.timeout` in `.golangci.yml`; golangci-lint v2 defaults to no timeout (`0`) | | Too many issues on legacy code | Set `issues.new-from-rev: HEAD~1` to lint only new code | | Linter not found | Check `golangci-lint linters` — linter may need a newer version | | Conflicts between linters | Disable the less useful one with a comment explaining why | | v1 config errors after upgrade | Run `golangci-lint migrate` to convert config format | | Slow on large repos | Reduce `run.concurrency` or exclude paths with `linters.exclusions.paths` / `formatters.exclusions.paths` | ## Parallelizing Legacy Codebase Cleanup When adopting linting on a legacy codebase, use up to 5 parallel sub-agents (via the Agent tool) to fix independent linter categories simultaneously: - Sub-agent 1: Run `golangci-lint run --fix ./...` for auto-fixable issues - Sub-agent 2: Fix security linter findings (bodyclose, sqlclosecheck, gosec) - Sub-agent 3: Fix error handling issues (errcheck, nilerr, wrapcheck) - Sub-agent 4: Fix style and formatting (gofumpt, goimports, revive) - Sub-agent 5: Fix code quality (gocritic, unused, ineffassign) ## Cross-References - → See `samber/cc-skills-golang@golang-continuous-integration` skill for CI pipeline with golangci-lint-action - → See `samber/cc-skills-golang@golang-code-style` skill for style rules that linters enforce - → See `samber/cc-skills-golang@golang-security` skill for SAST tools beyond linting (gosec, govulncheck) - → See `samber/cc-skills-golang@golang-continuous-integration` skill for automated AI-driven code review in CI using these guidelines ## Dónde encaja - Categoría: [Herramientas para desarrolladores](https://skillsagentes.com/categorias/herramientas-desarrollo.md) — Skills que cambian cómo tu agente escribe, revisa y despliega código. - Creador: [samber](https://skillsagentes.com/creators/samber.md) — 0 skills en el directorio - [Todas las skills](https://skillsagentes.com/skills.md) - [Ranking de instalaciones](https://skillsagentes.com/ranking.md) ## Otras skills del mismo repositorio - [Golang How To](https://skillsagentes.com/skills/samber/cc-skills-golang/golang-how-to.md): Orquestador de skills de Golang, siempre activo en cualquier tarea de código, revisión, debug o setup: carga las skills más relevantes de samber/cc-skills-golang, a menudo varias a la vez. - [Golang Benchmark](https://skillsagentes.com/skills/samber/cc-skills-golang/golang-benchmark.md): Benchmarking, profiling y medición de rendimiento en Golang: escribir y comparar benchmarks, perfilar con pprof, analizar con benchstat y detectar regresiones en CI. - [Golang Performance](https://skillsagentes.com/skills/samber/cc-skills-golang/golang-performance.md): Patrones y metodología de optimización de rendimiento en Golang: si hay cuello de botella X, aplica el patrón Y, una vez que profiling o benchmarks ya lo identificaron. - [Golang Testing](https://skillsagentes.com/skills/samber/cc-skills-golang/golang-testing.md): Tests de Golang listos para producción: table-driven, suites y mocks con testify, tests paralelos, fuzzing, fixtures, detección de fugas de goroutines con goleak, snapshot testing, cobertura, tests de integración. - [Golang Troubleshooting](https://skillsagentes.com/skills/samber/cc-skills-golang/golang-troubleshooting.md): Depura programas Go de forma sistemática hasta encontrar y corregir la causa raíz: metodología de debugging, errores comunes de Go, pprof, Delve, detección de races y depuración en producción. ## Skills relacionadas - [Golang Samber Hot](https://skillsagentes.com/skills/samber/cc-skills-golang/golang-samber-hot.md): Caché en memoria en Golang con samber/hot: algoritmos de expulsión (LRU, LFU, TinyLFU, S3FIFO, ARC, TwoQueue, SIEVE, FIFO), TTL, loaders, sharding y métricas Prometheus. - [Golang Samber Lo](https://skillsagentes.com/skills/samber/cc-skills-golang/golang-samber-lo.md): Helpers funcionales para Go con samber/lo: 500+ funciones genéricas type-safe para slices, maps, canales, strings, math, tuplas y concurrencia. - [Golang Samber Mo](https://skillsagentes.com/skills/samber/cc-skills-golang/golang-samber-mo.md): Tipos monádicos para Golang con samber/mo — Option, Result, Either, Future, IO, Task y State para valores nulos seguros, manejo de errores y composición funcional. - [Golang Samber Slog](https://skillsagentes.com/skills/samber/cc-skills-golang/golang-samber-slog.md): Extensiones de logging estructurado para Go con paquetes samber/slog-****: pipelines multi-handler, sampling, formateo de atributos, middleware HTTP y enrutamiento a backends como Datadog, Sentry o Loki. - [Golang Spf13 Viper](https://skillsagentes.com/skills/samber/cc-skills-golang/golang-spf13-viper.md): Librería de configuración en Go con spf13/viper: precedencia en capas (flag > env > archivo > KV > default), BindPFlag, AutomaticEnv, Unmarshal con mapstructure, Sub, WatchConfig y aislamiento en tests. --- Skills Agentes · [Índice de páginas en markdown](https://skillsagentes.com/sitemap.md) · [Inicio](https://skillsagentes.com/index.md)