4.6 KiB
4.6 KiB
Go Linting 配置說明
本項目使用現代化的 Go linting 工具來確保代碼質量和風格一致性。
工具介紹
golangci-lint
- 現代化的 Go linter 聚合工具,整合了多個 linter
- 比傳統的
golint
更快、更全面 - 支持並行執行和緩存
- 配置文件:
.golangci.yml
安裝
安裝 golangci-lint
# macOS
brew install golangci-lint
# Linux
curl -sSfL https://raw.githubusercontent.com/golangci/golangci-lint/master/install.sh | sh -s -- -b $(go env GOPATH)/bin v1.55.2
# Windows
go install github.com/golangci/golangci-lint/cmd/golangci-lint@v1.55.2
安裝其他工具
# 格式化工具
go install mvdan.cc/gofumpt@latest
go install golang.org/x/tools/cmd/goimports@latest
使用方法
Makefile 命令
# 基本代碼檢查
make lint
# 自動修復可修復的問題
make lint-fix
# 詳細輸出
make lint-verbose
# 只檢查新問題(與 main 分支比較)
make lint-new
# 格式化代碼
make fmt
直接使用 golangci-lint
# 基本檢查
golangci-lint run
# 自動修復
golangci-lint run --fix
# 檢查特定目錄
golangci-lint run ./pkg/...
# 詳細輸出
golangci-lint run -v
# 只顯示新問題
golangci-lint run --new-from-rev=main
配置說明
啟用的 Linters
我們的配置啟用了以下 linter 類別:
核心檢查
errcheck
: 檢查未處理的錯誤gosimple
: 簡化代碼建議govet
: 檢查常見錯誤staticcheck
: 靜態分析typecheck
: 類型檢查unused
: 檢查未使用的變量和函數
代碼質量
cyclop
: 循環複雜度檢查dupl
: 代碼重複檢測funlen
: 函數長度檢查gocognit
: 認知複雜度檢查gocyclo
: 循環複雜度檢查nestif
: 嵌套深度檢查
格式化
gofmt
: 格式化檢查gofumpt
: 更嚴格的格式化goimports
: 導入排序
命名和風格
goconst
: 常量檢查gocritic
: 代碼評論gomnd
: 魔術數字檢查stylecheck
: 風格檢查varnamelen
: 變量名長度檢查
安全
gosec
: 安全檢查
錯誤處理
errorlint
: 錯誤處理檢查nilerr
: nil 錯誤檢查wrapcheck
: 錯誤包裝檢查
配置文件結構
# .golangci.yml
run:
timeout: 5m
skip-dirs: [vendor, .git, bin, build, dist, tmp]
skip-files: [".*\\.pb\\.go$", ".*\\.gen\\.go$"]
linters:
disable-all: true
enable: [errcheck, gosimple, govet, ...]
linters-settings:
# 各個 linter 的詳細配置
issues:
# 問題排除規則
exclude-rules:
- path: _test\.go
linters: [gomnd, funlen, dupl]
IDE 整合
VS Code
項目包含 .vscode/settings.json
配置:
- 自動使用 golangci-lint 進行檢查
- 保存時自動格式化
- 使用 gofumpt 作為格式化工具
GoLand/IntelliJ
- 安裝 golangci-lint 插件
- 在設置中指向項目的
.golangci.yml
文件
CI/CD 整合
GitHub Actions
項目包含 .github/workflows/ci.yml
:
- 自動運行測試
- 執行 golangci-lint 檢查
- 安全掃描
- 依賴檢查
本地 Git Hooks
可以設置 pre-commit hook:
#!/bin/sh
# .git/hooks/pre-commit
make lint
常見問題
1. 如何忽略特定的檢查?
在代碼中使用註釋:
//nolint:gosec // 忽略安全檢查
password := "hardcoded"
//nolint:lll // 忽略行長度檢查
url := "https://very-long-url-that-exceeds-line-length-limit.com/api/v1/endpoint"
2. 如何為測試文件設置不同的規則?
配置文件中已經為測試文件設置了特殊規則:
exclude-rules:
- path: _test\.go
linters: [gomnd, funlen, dupl, lll, goconst]
3. 如何調整複雜度閾值?
在 .golangci.yml
中調整:
linters-settings:
cyclop:
max-complexity: 15 # 調整循環複雜度
funlen:
lines: 100 # 調整函數行數限制
statements: 50 # 調整語句數限制
4. 性能優化
- 使用緩存:
golangci-lint cache clean
清理緩存 - 只檢查修改的文件:
--new-from-rev=main
- 並行執行:默認已啟用
升級和維護
定期更新 golangci-lint:
# 檢查版本
golangci-lint version
# 升級到最新版本
brew upgrade golangci-lint # macOS
# 或重新下載安裝腳本
定期檢查配置文件的新選項和 linter:
# 查看所有可用的 linter
golangci-lint linters
# 查看配置幫助
golangci-lint config -h