golangci-lint

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese

golangci-lint

golangci-lint

golangci-lint is a fast, parallel Go linters aggregator. It runs dozens of linters concurrently, caches results, and reports issues in a unified output. Use this skill to install, configure, run, and integrate golangci-lint into Go projects.
golangci-lint是一款快速、并行的Go语言代码检查工具聚合器。它可以同时运行数十款代码检查工具,缓存检查结果,并以统一格式输出问题报告。本技能将指导你完成golangci-lint的安装、配置、运行,以及将其集成到Go项目中的操作。

Installation

安装

Binary (Recommended)

二进制安装(推荐方式)

Install a pinned version into
$(go env GOPATH)/bin
:
bash
curl -sSfL https://golangci-lint.run/install.sh | sh -s -- -b $(go env GOPATH)/bin v2.10.1
golangci-lint --version
Install into a local
./bin/
directory instead:
bash
curl -sSfL https://golangci-lint.run/install.sh | sh -s v2.10.1
将指定版本安装到
$(go env GOPATH)/bin
目录:
bash
curl -sSfL https://golangci-lint.run/install.sh | sh -s -- -b $(go env GOPATH)/bin v2.10.1
golangci-lint --version
或者安装到本地
./bin/
目录:
bash
curl -sSfL https://golangci-lint.run/install.sh | sh -s v2.10.1

macOS

macOS系统

bash
brew install golangci-lint
bash
brew install golangci-lint

or tap for the latest release

或者通过tap安装最新版本

brew tap golangci/tap && brew install golangci/tap/golangci-lint
undefined
brew tap golangci/tap && brew install golangci/tap/golangci-lint
undefined

Windows

Windows系统

bash
choco install golangci-lint   # Chocolatey
scoop install main/golangci-lint  # Scoop
bash
choco install golangci-lint   # Chocolatey包管理器
scoop install main/golangci-lint  # Scoop包管理器

Docker

Docker方式

bash
docker run --rm -v $(pwd):/app -w /app golangci/golangci-lint:v2.10.1 golangci-lint run
Always pin to a specific version in CI. Avoid
go install
for golangci-lint — binary installation is faster and more reproducible.
bash
docker run --rm -v $(pwd):/app -w /app golangci/golangci-lint:v2.10.1 golangci-lint run
在CI环境中请始终固定使用特定版本。避免使用
go install
安装golangci-lint——二进制安装方式更快且结果更可复现。

Running

运行

Basic Commands

基础命令

bash
undefined
bash
undefined

Lint the entire module (recursive)

检查整个模块(递归)

golangci-lint run
golangci-lint run

Equivalent explicit form

等效的显式写法

golangci-lint run ./...
golangci-lint run ./...

Lint specific directories or files

检查指定目录或文件

golangci-lint run ./pkg/... ./internal/... golangci-lint run main.go
golangci-lint run ./pkg/... ./internal/... golangci-lint run main.go

Format code

格式化代码

golangci-lint fmt
golangci-lint fmt

List enabled/available linters

列出启用/可用的代码检查工具

golangci-lint linters golangci-lint help linters

Directories are not analyzed recursively by default — append `/...` to recurse.
golangci-lint linters golangci-lint help linters

默认情况下不会递归分析目录——需追加`/...`来启用递归。

Useful Flags

实用参数

FlagPurpose
--fix
Auto-fix issues where supported
--fast
Run only fast linters
-E <linter>
Enable a specific linter
-D <linter>
Disable a specific linter
--default=none
Disable all default linters
--timeout 5m
Set analysis timeout
-v
Verbose output (shows which config is loaded)
--new-from-rev HEAD~1
Report only issues in recent changes
参数用途
--fix
自动修复支持该功能的问题
--fast
仅运行快速检查工具
-E <linter>
启用指定的代码检查工具
-D <linter>
禁用指定的代码检查工具
--default=none
禁用所有默认检查工具
--timeout 5m
设置分析超时时间
-v
详细输出(显示加载的配置文件)
--new-from-rev HEAD~1
仅报告最近变更中出现的问题

Show Only New Issues

仅显示新增问题

Integrate into existing codebases without fixing everything at once:
bash
undefined
在现有代码库中集成时,无需一次性修复所有问题:
bash
undefined

Show only issues in uncommitted changes

仅显示未提交变更中的问题

golangci-lint run --new
golangci-lint run --new

Show only issues introduced since a commit

仅显示指定提交之后引入的问题

golangci-lint run --new-from-rev HEAD~1
undefined
golangci-lint run --new-from-rev HEAD~1
undefined

Configuration File

配置文件

golangci-lint searches for these files from the working directory upward:
  • .golangci.yml
    /
    .golangci.yaml
  • .golangci.toml
  • .golangci.json
All config-file options mirror CLI flags. Linter-specific settings are only available via the config file.
golangci-lint会从当前工作目录向上搜索以下配置文件:
  • .golangci.yml
    /
    .golangci.yaml
  • .golangci.toml
  • .golangci.json
所有配置文件选项与CLI参数一一对应。检查工具的特定设置仅能通过配置文件实现。

Minimal Working Configuration

最简可用配置

yaml
version: "2"

linters:
  default: standard
  enable:
    - gocritic
    - gosec
    - misspell
    - revive
    - wrapcheck

run:
  timeout: 5m
  tests: true

issues:
  max-issues-per-linter: 0
  max-same-issues: 0
yaml
version: "2"

linters:
  default: standard
  enable:
    - gocritic
    - gosec
    - misspell
    - revive
    - wrapcheck

run:
  timeout: 5m
  tests: true

issues:
  max-issues-per-linter: 0
  max-same-issues: 0

Recommended Project Configuration

推荐项目配置

yaml
version: "2"

linters:
  default: standard
  enable:
    - bodyclose
    - errorlint
    - gocritic
    - gosec
    - misspell
    - noctx
    - revive
    - staticcheck
    - wrapcheck
  disable:
    - exhaustruct   # too noisy for most projects

run:
  timeout: 5m
  tests: true
  relative-path-mode: gomod

issues:
  max-issues-per-linter: 0
  max-same-issues: 0
  new-from-rev: ""  # report all issues, not just new ones

linters:
  exclusions:
    generated: lax
    presets:
      - comments
      - std-error-handling
    rules:
      - path: _test\.go
        linters:
          - gosec
          - errcheck
          - funlen
yaml
version: "2"

linters:
  default: standard
  enable:
    - bodyclose
    - errorlint
    - gocritic
    - gosec
    - misspell
    - noctx
    - revive
    - staticcheck
    - wrapcheck
  disable:
    - exhaustruct   # 对大多数项目来说过于繁琐

run:
  timeout: 5m
  tests: true
  relative-path-mode: gomod

issues:
  max-issues-per-linter: 0
  max-same-issues: 0
  new-from-rev: ""  # 报告所有问题,而非仅新增问题

linters:
  exclusions:
    generated: lax
    presets:
      - comments
      - std-error-handling
    rules:
      - path: _test\.go
        linters:
          - gosec
          - errcheck
          - funlen

Linters

代码检查工具(Linters)

Enabled by Default (
default: standard
)

默认启用的工具(
default: standard

LinterPurpose
errcheck
Detects unchecked errors
govet
Finds suspicious constructs (like
go vet
)
ineffassign
Detects assignments to variables that are never used
staticcheck
Comprehensive static analysis suite
unused
Finds unused constants, variables, functions, and types
工具用途
errcheck
检测未处理的错误
govet
查找可疑代码结构(类似
go vet
ineffassign
检测赋值后从未使用的变量
staticcheck
全面的静态分析套件
unused
查找未使用的常量、变量、函数和类型

Commonly Enabled Extra Linters

常用额外启用的工具

LinterPurpose
bodyclose
Checks HTTP response body is closed
errorlint
Finds issues with Go 1.13 error wrapping
gocritic
Bugs, performance, and style diagnostics
gosec
Security-focused code inspection
misspell
Finds commonly misspelled English words
noctx
Detects missing
context.Context
usage
revive
Configurable drop-in replacement for
golint
wrapcheck
Ensures errors from external packages are wrapped
funlen
Reports functions exceeding a length threshold
gocyclo
Cyclomatic complexity checker
godot
Checks comments end with a period
prealloc
Suggests slice pre-allocation
unparam
Reports unused function parameters
Run
golangci-lint help linters
to see all available linters with their status.
工具用途
bodyclose
检查HTTP响应体是否已关闭
errorlint
查找Go 1.13错误包装的问题
gocritic
检测bug、性能和代码风格问题
gosec
聚焦安全的代码检查
misspell
查找常见的英文拼写错误
noctx
检测缺失
context.Context
的使用场景
revive
可配置的
golint
替代工具
wrapcheck
确保外部包返回的错误已被包装
funlen
报告长度超过阈值的函数
gocyclo
圈复杂度检查器
godot
检查注释是否以句号结尾
prealloc
建议预分配切片
unparam
报告未使用的函数参数
运行
golangci-lint help linters
可查看所有可用工具及其状态。

Suppressing False Positives

屏蔽误报

Inline
//nolint
Directive

行内
//nolint
指令

Suppress for a single line:
go
var legacyVar = globalState //nolint:gochecknoglobals // legacy API contract
Suppress multiple linters:
go
result, _ := riskyCall() //nolint:errcheck,gosec
Suppress for an entire function:
go
//nolint:gocyclo // This legacy function is intentionally complex
func parseLegacyConfig() error {
    // ...
}
Syntax rules — no spaces allowed between
//
and
nolint
, or between
nolint:
and the linter name:
go
// nolint:xxx   ← INVALID (space after //)
//nolint: xxx   ← INVALID (space after colon)
//nolint:xxx    ← VALID
Always add a comment after
//nolint
explaining why.
屏蔽单行代码的检查:
go
var legacyVar = globalState //nolint:gochecknoglobals // 遗留API约定
屏蔽多个工具的检查:
go
result, _ := riskyCall() //nolint:errcheck,gosec
屏蔽整个函数的检查:
go
//nolint:gocyclo // 该遗留函数设计即为复杂
func parseLegacyConfig() error {
    // ...
}
语法规则——
//
nolint
之间、
nolint:
与工具名称之间不允许有空格:
go
// nolint:xxx   ← 无效(//后有空格)
//nolint: xxx   ← 无效(冒号后有空格)
//nolint:xxx    ← 有效
请始终在
//nolint
后添加注释说明原因。

Exclusion Rules in Config

配置文件中的排除规则

Exclude by path pattern:
yaml
linters:
  exclusions:
    rules:
      - path: _test\.go
        linters:
          - gocyclo
          - errcheck
          - gosec
Exclude by issue text:
yaml
linters:
  exclusions:
    rules:
      - linters:
          - staticcheck
        text: "SA9003:"
Exclude generated files:
yaml
linters:
  exclusions:
    generated: lax   # also excludes files with "do not edit" comments
    paths:
      - vendor/
      - ".*\\.pb\\.go$"
按路径模式排除:
yaml
linters:
  exclusions:
    rules:
      - path: _test\.go
        linters:
          - gocyclo
          - errcheck
          - gosec
按问题文本排除:
yaml
linters:
  exclusions:
    rules:
      - linters:
          - staticcheck
        text: "SA9003:"
排除生成的文件:
yaml
linters:
  exclusions:
    generated: lax   # 同时排除包含"do not edit"注释的文件
    paths:
      - vendor/
      - ".*\\.pb\\.go$"

Exclusion Presets

排除预设

Four built-in presets group common false-positive suppressions:
yaml
linters:
  exclusions:
    presets:
      - comments            # unexported items without godoc
      - std-error-handling  # ignores Close/Flush/Print error checks
      - common-false-positives  # gosec G103, G204, G304
      - legacy              # deprecated rules from older linters
内置四个预设分组,用于屏蔽常见的误报:
yaml
linters:
  exclusions:
    presets:
      - comments            # 未导出项无godoc注释
      - std-error-handling  # 忽略Close/Flush/Print的错误检查
      - common-false-positives  # gosec的G103、G204、G304规则
      - legacy              # 旧版检查工具的废弃规则

CI Integration

CI集成

GitHub Actions

GitHub Actions

yaml
name: Lint
on: [push, pull_request]
jobs:
  lint:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v4
      - uses: actions/setup-go@v5
        with:
          go-version: stable
      - uses: golangci/golangci-lint-action@v6
        with:
          version: v2.10.1
Use the official
golangci/golangci-lint-action
— it uses smart caching and creates GitHub annotations for found issues.
yaml
name: Lint
on: [push, pull_request]
jobs:
  lint:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v4
      - uses: actions/setup-go@v5
        with:
          go-version: stable
      - uses: golangci/golangci-lint-action@v6
        with:
          version: v2.10.1
推荐使用官方
golangci/golangci-lint-action
——它支持智能缓存,并能在GitHub中为发现的问题添加注解。

GitLab CI

GitLab CI

yaml
include:
  - component: $CI_SERVER_FQDN/components/code-quality-oss/codequality-os-scanners-integration/golangci@1.0.1
yaml
include:
  - component: $CI_SERVER_FQDN/components/code-quality-oss/codequality-os-scanners-integration/golangci@1.0.1

Other CI (Binary)

其他CI环境(二进制方式)

bash
curl -sSfL https://golangci-lint.run/install.sh | sh -s -- -b /usr/local/bin v2.10.1
golangci-lint run ./...
Always pin to a specific version to prevent unexpected breakage when linters are upgraded upstream.
bash
curl -sSfL https://golangci-lint.run/install.sh | sh -s -- -b /usr/local/bin v2.10.1
golangci-lint run ./...
请始终固定使用特定版本,避免上游工具升级导致意外故障。

Output Formats

输出格式

golangci-lint supports multiple output formats for different consumers:
yaml
output:
  formats:
    text:
      path: stdout
      print-linter-name: true
    json:
      path: ./lint-report.json
    checkstyle:
      path: ./checkstyle-report.xml
    junit-xml:
      path: ./junit-report.xml
    sarif:
      path: ./sarif-report.json
  sort-order:
    - linter
    - severity
    - file
golangci-lint支持多种输出格式,以适配不同场景:
yaml
output:
  formats:
    text:
      path: stdout
      print-linter-name: true
    json:
      path: ./lint-report.json
    checkstyle:
      path: ./checkstyle-report.xml
    junit-xml:
      path: ./junit-report.xml
    sarif:
      path: ./sarif-report.json
  sort-order:
    - linter
    - severity
    - file

Quick Reference

快速参考

CommandPurpose
golangci-lint run
Lint entire module
golangci-lint run --fix
Lint and auto-fix
golangci-lint fmt
Format code
golangci-lint linters
List enabled linters
golangci-lint run -v
Verbose (shows config path)
golangci-lint run --new
Only new issues in changed files
Config fileSearch order
.golangci.yml
First match wins, searches upward
.golangci.yaml
Second
.golangci.toml
Third
.golangci.json
Fourth
命令用途
golangci-lint run
检查整个模块
golangci-lint run --fix
检查并自动修复问题
golangci-lint fmt
格式化代码
golangci-lint linters
列出已启用的检查工具
golangci-lint run -v
详细输出(显示配置文件路径)
golangci-lint run --new
仅显示变更文件中的新增问题
配置文件搜索顺序
.golangci.yml
找到第一个匹配项即停止,向上递归搜索
.golangci.yaml
第二优先级
.golangci.toml
第三优先级
.golangci.json
第四优先级

Additional Resources

额外资源

For complete configuration examples, linter-by-linter settings, and advanced patterns:
  • references/advanced-configuration.md
    — Full
    .golangci.yml
    with all sections annotated, per-linter settings examples, and CI caching strategies
如需完整的配置示例、各检查工具的详细设置以及高级使用模式,请参考:
  • references/advanced-configuration.md
    —— 带全注解的完整
    .golangci.yml
    配置、各检查工具设置示例,以及CI缓存策略