背景:下面的實踐是在golang 1.19版本下進行的
什么是lint
lint是用來進行代碼的靜態(tài)分析工具。既在不運行代碼的前提下,找出代碼中不規(guī)范以及存在bug的地方。存在各種各樣的lint
golangci-lint
golangci-lint提供了豐富的linter框架,通過配置可以選擇開啟或關(guān)閉特定的linter。
實踐
- 安裝
GOPATH_FIRST=$(echo $(go env GOPATH) | awk -F':' '{ print $1}')
curl -sfL https://install.goreleaser.com/github.com/golangci/golangci-lint.sh | sh -s -- -b ${GOPATH_FIRST}/bin v1.21.0
或者采用下面命令
go install github.com/golangci/golangci-lint/cmd/golangci-lint
- 配置golangci-lint
在項目根目錄下新建.golangci.yml文件,文件內(nèi)容如下:
linters:
disable-all: true # 關(guān)閉其他linter
enable: # 下面是開啟的linter列表,之后的英文注釋介紹了相應(yīng)linter的功能
- deadcode # Finds unused code
# - errcheck # Errcheck is a program for checking for unchecked errors in go programs. These unchecked errors can be critical bugs in some cases
- gosimple # Linter for Go source code that specializes in simplifying a code
- govet # Vet examines Go source code and reports suspicious constructs, such as Printf calls whose arguments do not align with the format string
- ineffassign # Detects when assignments to existing variables are not used
- staticcheck # Staticcheck is a go vet on steroids, applying a ton of static analysis checks
- structcheck # Finds unused struct fields
- typecheck # Like the front-end of a Go compiler, parses and type-checks Go code
- unused # Checks Go code for unused constants, variables, functions and types
- varcheck # Finds unused global variables and constants
- scopelint # Scopelint checks for unpinned variables in go programs
# - golint # Carry out the stylistic conventions put forth in Effective Go and CodeReviewComments
linters-settings:
govet: # 對于linter govet,我們手動開啟了它的某些掃描規(guī)則
check-shadowing: true
check-unreachable: true
check-rangeloops: true
check-copylocks: true
配置vscode(可選)
參考:https://itcn.blog/p/3347295113.html,主要是開啟golint配置使用
運行下面命令,即可進行檢查代碼。此命令會檢查當(dāng)前目錄下的.golangci.yml文件,然后輸出結(jié)果
golangci-lint run