命令
golangci-lint run --config=.golangci.yml ./...
Go
# 检查当前项目
golangci-lint run --config=.golangci.yml ./...
# 自动修复可修复的问题
golangci-lint run --fix --config=.golangci.yml ./...
# 清理缓存
golangci-lint cache clean
配置文件.golangci.yml
Go
linters:
# Disable all linters.
# Default: false
disable-all: true
# Enable specific linter
# https://golangci-lint.run/usage/linters/#enabled-by-default
enable:
- errcheck
- gosimple
- govet
- ineffassign
- staticcheck
- unused
- gocyclo
- revive
linters-settings:
gocyclo:
# Minimal code complexity to report.
# Default: 30 (but we recommend 10-20)
min-complexity: 15
revive:
ignore-generated-header: true
severity: warning
rules:
- name: atomic
- name: blank-imports
- name: context-as-argument
- name: context-keys-type
- name: dot-imports
- name: error-return
- name: error-strings
- name: error-naming
- name: exported
- name: increment-decrement
- name: var-naming
severity: warning
disabled: false
exclude: [""]
arguments:
- ["ID","IDS","UID","URL","JSON","API","URL", "IP"]
- []
- - skipPackageNameChecks: true
- name: var-declaration
- name: package-comments
- name: range
- name: receiver-naming
- name: time-naming
- name: unexported-return
- name: indent-error-flow
- name: errorf
- name: empty-block
- name: superfluous-else
- name: unused-parameter
- name: unreachable-code
- name: redefines-builtin-id
# typecheck:
# parallelism: 4
# # 设置是否检查内部包和外部包
# mode: strict
###配置详解
```
linters:
disable-all: true # 禁用所有默认 linter
enable: # 只启用指定的 linter
-
errcheck
-
gosimple
-
govet
-
ineffassign
-
staticcheck
-
unused
-
gocyclo
-
revive
```
1. 启用的 Linter 说明
Linter 作用 示例 errcheck 检查未处理的错误 f.Close() 未检查返回的 error gosimple 代码简化建议 if x { return true } else { return false } → return x govet Go 静态分析 检测 Printf 格式字符串错误 ineffassign 无效赋值检测 x = 1 后未使用 x staticcheck 综合静态分析 未使用的变量、错误的代码模式 unused 未使用代码检测 未使用的函数、变量、常量 gocyclo 圈复杂度检测 函数过于复杂 revive 代码风格检查 命名规范、注释规范等
2. gocyclo 配置
```
gocyclo:
min-complexity: 15 # 圈复杂度超过 15 报警
```
圈复杂度示例:
```
// 复杂度 = 1 (基础) + if/for/case 分支数
func Example(a, b int) {
if a > 0 { // +1
for i := 0; i < b; i++ { // +1
switch i { // +1
case 1: // +1
case 2: // +1
}
}
}
}
// 总复杂度 = 6
```
3. revive 规则详解
```
revive:
ignore-generated-header: true # 忽略生成文件的头部
severity: warning # 默认严重级别
rules:
``` 关键规则说明
规则 作用 示例 atomic 原子操作检查 atomic.Add 使用正确性 blank-imports 空白导入检查 _ "driver" 是否必要 context-as-argument context 参数位置 context 应为第一个参数 error-return 错误返回检查 错误应作为最后一个返回值 error-naming 错误命名规范 ErrNotFound 而非 ErrorNotFound exported 导出元素注释 大写开头元素需有注释 var-naming 变量命名规范 驼峰命名,特定缩写允许 unused-parameter 未使用参数 参数未使用应改为 _ unreachable-code 不可达代码 return 后的代码