網(wǎng)站項目策劃書實例/網(wǎng)絡(luò)推廣深圳有效渠道
GolangCI-Lint配置變更實踐
Golang編程中,為了便于調(diào)試和代碼質(zhì)量和安全性檢查。利用該方法可以在開發(fā)周期的早期捕獲錯誤,并且檢查團(tuán)隊編程風(fēng)格,提高一致性。這對團(tuán)隊協(xié)作開發(fā)特別有用,可以提高開發(fā)的效率,保持代碼質(zhì)量和安全性。
本實踐所有測試內(nèi)容都使用以下代碼進(jìn)行測試
package mainimport ("database/sql""fmt""log""net/http""strings"_ "github.com/go-sql-driver/mysql"
)var db *sql.DBfunc main() {// 連接到數(shù)據(jù)庫var err errordb, err = sql.Open("mysql", "username:password@tcp(localhost:3306)/mydatabase")if err != nil {log.Fatal(err)}defer db.Close()http.HandleFunc("/search", searchHandler)http.ListenAndServe(":8080", nil)
}func searchHandler(w http.ResponseWriter, r *http.Request) {query := r.URL.Query().Get("query")// 構(gòu)建SQL查詢字符串(易受SQL注入攻擊)sqlQuery := "SELECT name, age FROM users WHERE name = '" + query + "'"rows, err := db.Query(sqlQuery)if err != nil {log.Println("Error executing query:", err)return}defer rows.Close()var name stringvar age intfor rows.Next() {err := rows.Scan(&name, &age)if err != nil {log.Println("Error scanning row:", err)continue}fmt.Fprintf(w, "Name: %s, Age: %d\n", name, age)}
}
概述
開發(fā)更全面的linting工具的是golang社區(qū)的一個熱門開發(fā)領(lǐng)域。社區(qū)產(chǎn)生了大量的linter模塊,每個都有特定的目的。比如:
Unused:用于檢查Golang代碼中未使用的常量、變量、函數(shù)和類型。
Goconst:查找可以被常量替換的重復(fù)字符串。
Gocyclo:計算并檢查函數(shù)的cyclomatic復(fù)雜度。
Errcheck:檢測Golang代碼中無法檢查到的錯誤。
面對這么多的linting模塊,開發(fā)者必須自己下載每個單獨的linter并管理它們的版本。此外,按順序運行它們中的每一個可能太慢,因此引入了golang ci-lint,這是一個并行運行l(wèi)inters的 Go linters 聚合器,重用Go構(gòu)建緩存,并緩存分析結(jié)果以大大提高后續(xù)運行的性能。
出于方便和性能原因,該項目旨在并行聚合和運行多個單獨的linter。當(dāng)安裝該程序時,將獲得大約48個linter檢查器,用戶可以繼續(xù)挑選特定的檢查器以適合自己的實際情況和需求。除了能夠在開發(fā)調(diào)試時候在本地運行之外,還可以將linting加入到CI/CD和DevOps流程中,自動的、持續(xù)集成的進(jìn)行檢查測試。
安裝
使用go install 安裝golangci-lint,支持在有g(shù)olang開發(fā)環(huán)境的任何操作系統(tǒng)上本地安裝。也可以在官方下載特定操作系統(tǒng)下的二進(jìn)制包安裝。
比如在macOS下可以使用brew安裝:
brew install golangci-lint
brew upgrade golangci-lint
簡單用法
安裝后,通過以下命令查看版本:
golangci-lint version
golangci-lint has version 1.55.1 built with go1.21.3 from 9b20d49 on 2023-10-24T12:38:15Z
可以通過 help linter命令查看當(dāng)前啟用的linter規(guī)則,可以看到gosec默認(rèn)是關(guān)閉的:
golangci-lint help linters
Enabled by default linters:
errcheck: errcheck is a program for checking for unchecked errors in Go code. These unchecked errors can be critical bugs in some cases [fast: false, auto-fix: false]
gosimple (megacheck): Linter for Go source code that specializes in simplifying code [fast: false, auto-fix: false]
govet (vet, vetshadow): Vet examines Go source code and reports suspicious constructs, such as Printf calls whose arguments do not align with the format string [fast: false, auto-fix: false]
ineffassign: Detects when assignments to existing variables are not used [fast: true, auto-fix: false]
staticcheck (megacheck): It's a set of rules from staticcheck. It's not the same thing as the staticcheck binary. The author of staticcheck doesn't support or approve the use of staticcheck as a library inside golangci-lint. [fast: false, auto-fix: false]
unused (megacheck): Checks Go code for unused constants, variables, functions and types [fast: false, auto-fix: false]Disabled by default linters:
asasalint: check for pass []any as any in variadic func(...any) [fast: false, auto-fix: false]
asciicheck: Simple linter to check that your code does not contain non-ASCII identifiers [fast: true, auto-fix: false]
bidichk: Checks for dangerous unicode character sequences [fast: true, auto-fix: false]
bodyclose: checks whether HTTP response body is closed successfully [fast: false, auto-fix: false]
containedctx: containedctx is a linter that detects struct contained context.Context field [fast: false, auto-fix: false]
contextcheck: check whether the function uses a non-inherited context [fast: false, auto-fix: false]
cyclop: checks function and package cyclomatic complexity [fast: false, auto-fix: false]
deadcode [deprecated]: Finds unused code [fast: false, auto-fix: false]
decorder: check declaration order and count of types, constants, variables and functions [fast: true, auto-fix: false]
depguard: Go linter that checks if package imports are in a list of acceptable packages [fast: true, auto-fix: false]
dogsled: Checks assignments with too many blank identifiers (e.g. x, _, _, _, := f()) [fast: true, auto-fix: false]
dupl: Tool for code clone detection [fast: true, auto-fix: false]
dupword: checks for duplicate words in the source code [fast: true, auto-fix: true]
durationcheck: check for two durations multiplied together [fast: false, auto-fix: false]
errchkjson: Checks types passed to the json encoding functions. Reports unsupported types and optionally reports occasions, where the check for the returned error can be omitted. [fast: false, auto-fix: false]
errname: Checks that sentinel errors are prefixed with the `Err` and error types are suffixed with the `Error`. [fast: false, auto-fix: false]
errorlint: errorlint is a linter for that can be used to find code that will cause problems with the error wrapping scheme introduced in Go 1.13. [fast: false, auto-fix: false]
execinquery: execinquery is a linter about query string checker in Query function which reads your Go src files and warning it finds [fast: false, auto-fix: false]
exhaustive: check exhaustiveness of enum switch statements [fast: false, auto-fix: false]
exhaustivestruct [deprecated]: Checks if all struct's fields are initialized [fast: false, auto-fix: false]
exhaustruct: Checks if all structure fields are initialized [fast: false, auto-fix: false]
exportloopref: checks for pointers to enclosing loop variables [fast: false, auto-fix: false]
forbidigo: Forbids identifiers [fast: false, auto-fix: false]
forcetypeassert: finds forced type assertions [fast: true, auto-fix: false]
funlen: Tool for detection of long functions [fast: true, auto-fix: false]
gci: Gci controls Go package import order and makes it always deterministic. [fast: true, auto-fix: false]
ginkgolinter: enforces standards of using ginkgo and gomega [fast: false, auto-fix: false]
gocheckcompilerdirectives: Checks that go compiler directive comments (//go:) are valid. [fast: true, auto-fix: false]
gochecknoglobals: check that no global variables exist [fast: false, auto-fix: false]
gochecknoinits: Checks that no init functions are present in Go code [fast: true, auto-fix: false]
gochecksumtype: Run exhaustiveness checks on Go "sum types" [fast: false, auto-fix: false]
gocognit: Computes and checks the cognitive complexity of functions [fast: true, auto-fix: false]
goconst: Finds repeated strings that could be replaced by a constant [fast: true, auto-fix: false]
gocritic: Provides diagnostics that check for bugs, performance and style issues. [fast: false, auto-fix: false]
gocyclo: Computes and checks the cyclomatic complexity of functions [fast: true, auto-fix: false]
godot: Check if comments end in a period [fast: true, auto-fix: true]
godox: Tool for detection of FIXME, TODO and other comment keywords [fast: true, auto-fix: false]
goerr113: Go linter to check the errors handling expressions [fast: false, auto-fix: false]
gofmt: Gofmt checks whether code was gofmt-ed. By default this tool runs with -s option to check for code simplification [fast: true, auto-fix: true]
gofumpt: Gofumpt checks whether code was gofumpt-ed. [fast: true, auto-fix: true]
goheader: Checks is file header matches to pattern [fast: true, auto-fix: false]
goimports: Check import statements are formatted according to the 'goimport' command. Reformat imports in autofix mode. [fast: true, auto-fix: true]
golint [deprecated]: Golint differs from gofmt. Gofmt reformats Go source code, whereas golint prints out style mistakes [fast: false, auto-fix: false]
gomnd: An analyzer to detect magic numbers. [fast: true, auto-fix: false]
gomoddirectives: Manage the use of 'replace', 'retract', and 'excludes' directives in go.mod. [fast: true, auto-fix: false]
gomodguard: Allow and block list linter for direct Go module dependencies. This is different from depguard where there are different block types for example version constraints and module recommendations. [fast: true, auto-fix: false]
goprintffuncname: Checks that printf-like functions are named with `f` at the end [fast: true, auto-fix: false]
gosec (gas): Inspects source code for security problems [fast: false, auto-fix: false]
gosmopolitan: Report certain i18n/l10n anti-patterns in your Go codebase [fast: false, auto-fix: false]
grouper: An analyzer to analyze expression groups. [fast: true, auto-fix: false]
ifshort [deprecated]: Checks that your code uses short syntax for if-statements whenever possible [fast: true, auto-fix: false]
importas: Enforces consistent import aliases [fast: false, auto-fix: false]
inamedparam: reports interfaces with unnamed method parameters [fast: true, auto-fix: false]
interfacebloat: A linter that checks the number of methods inside an interface. [fast: true, auto-fix: false]
interfacer [deprecated]: Linter that suggests narrower interface types [fast: false, auto-fix: false]
ireturn: Accept Interfaces, Return Concrete Types [fast: false, auto-fix: false]
lll: Reports long lines [fast: true, auto-fix: false]
loggercheck (logrlint): Checks key value pairs for common logger libraries (kitlog,klog,logr,zap). [fast: false, auto-fix: false]
maintidx: maintidx measures the maintainability index of each function. [fast: true, auto-fix: false]
makezero: Finds slice declarations with non-zero initial length [fast: false, auto-fix: false]
maligned [deprecated]: Tool to detect Go structs that would take less memory if their fields were sorted [fast: false, auto-fix: false]
mirror: reports wrong mirror patterns of bytes/strings usage [fast: false, auto-fix: false]
misspell: Finds commonly misspelled English words in comments [fast: true, auto-fix: true]
musttag: enforce field tags in (un)marshaled structs [fast: false, auto-fix: false]
nakedret: Finds naked returns in functions greater than a specified function length [fast: true, auto-fix: false]
nestif: Reports deeply nested if statements [fast: true, auto-fix: false]
nilerr: Finds the code that returns nil even if it checks that the error is not nil. [fast: false, auto-fix: false]
nilnil: Checks that there is no simultaneous return of `nil` error and an invalid value. [fast: false, auto-fix: false]
nlreturn: nlreturn checks for a new line before return and branch statements to increase code clarity [fast: true, auto-fix: false]
noctx: noctx finds sending http request without context.Context [fast: false, auto-fix: false]
nolintlint: Reports ill-formed or insufficient nolint directives [fast: true, auto-fix: false]
nonamedreturns: Reports all named returns [fast: false, auto-fix: false]
nosnakecase [deprecated]: nosnakecase is a linter that detects snake case of variable naming and function name. [fast: true, auto-fix: false]
nosprintfhostport: Checks for misuse of Sprintf to construct a host with port in a URL. [fast: true, auto-fix: false]
paralleltest: paralleltest detects missing usage of t.Parallel() method in your Go test [fast: false, auto-fix: false]
perfsprint: Checks that fmt.Sprintf can be replaced with a faster alternative. [fast: false, auto-fix: false]
prealloc: Finds slice declarations that could potentially be pre-allocated [fast: true, auto-fix: false]
predeclared: find code that shadows one of Go's predeclared identifiers [fast: true, auto-fix: false]
promlinter: Check Prometheus metrics naming via promlint [fast: true, auto-fix: false]
protogetter: Reports direct reads from proto message fields when getters should be used [fast: false, auto-fix: true]
reassign: Checks that package variables are not reassigned [fast: false, auto-fix: false]
revive: Fast, configurable, extensible, flexible, and beautiful linter for Go. Drop-in replacement of golint. [fast: false, auto-fix: false]
rowserrcheck: checks whether Err of rows is checked successfully [fast: false, auto-fix: false]
scopelint [deprecated]: Scopelint checks for unpinned variables in go programs [fast: true, auto-fix: false]
sloglint: ensure consistent code style when using log/slog [fast: false, auto-fix: false]
sqlclosecheck: Checks that sql.Rows and sql.Stmt are closed. [fast: false, auto-fix: false]
structcheck [deprecated]: Finds unused struct fields [fast: false, auto-fix: false]
stylecheck: Stylecheck is a replacement for golint [fast: false, auto-fix: false]
tagalign: check that struct tags are well aligned [fast: true, auto-fix: true]
tagliatelle: Checks the struct tags. [fast: true, auto-fix: false]
tenv: tenv is analyzer that detects using os.Setenv instead of t.Setenv since Go1.17 [fast: false, auto-fix: false]
testableexamples: linter checks if examples are testable (have an expected output) [fast: true, auto-fix: false]
testifylint: Checks usage of github.com/stretchr/testify. [fast: false, auto-fix: false]
testpackage: linter that makes you use a separate _test package [fast: true, auto-fix: false]
thelper: thelper detects Go test helpers without t.Helper() call and checks the consistency of test helpers [fast: false, auto-fix: false]
tparallel: tparallel detects inappropriate usage of t.Parallel() method in your Go test codes [fast: false, auto-fix: false]
unconvert: Remove unnecessary type conversions [fast: false, auto-fix: false]
unparam: Reports unused function parameters [fast: false, auto-fix: false]
usestdlibvars: A linter that detect the possibility to use variables/constants from the Go standard library. [fast: true, auto-fix: false]
varcheck [deprecated]: Finds unused global variables and constants [fast: false, auto-fix: false]
varnamelen: checks that the length of a variable's name matches its scope [fast: false, auto-fix: false]
wastedassign: wastedassign finds wasted assignment statements. [fast: false, auto-fix: false]
whitespace: Tool for detection of leading and trailing whitespace [fast: true, auto-fix: true]
wrapcheck: Checks that errors returned from external packages are wrapped [fast: false, auto-fix: false]
wsl: Whitespace Linter - Forces you to use empty lines! [fast: true, auto-fix: false]
zerologlint: Detects the wrong usage of `zerolog` that a user forgets to dispatch with `Send` or `Msg`. [fast: false, auto-fix: false]Linters presets:
bugs: asasalint, asciicheck, bidichk, bodyclose, contextcheck, durationcheck, errcheck, errchkjson, errorlint, exhaustive, exportloopref, gocheckcompilerdirectives, gochecksumtype, gosec, gosmopolitan, govet, loggercheck, makezero, musttag, nilerr, noctx, protogetter, reassign, rowserrcheck, sqlclosecheck, staticcheck, testifylint, zerologlint
comment: dupword, godot, godox, misspell
complexity: cyclop, funlen, gocognit, gocyclo, maintidx, nestif
error: errcheck, errorlint, goerr113, wrapcheck
format: decorder, gci, gofmt, gofumpt, goimports, sloglint, tagalign
import: depguard, gci, goimports, gomodguard
metalinter: gocritic, govet, revive, staticcheck
module: depguard, gomoddirectives, gomodguard
performance: bodyclose, noctx, perfsprint, prealloc
sql: execinquery, rowserrcheck, sqlclosecheck
style: asciicheck, containedctx, decorder, depguard, dogsled, dupl, errname, exhaustruct, forbidigo, forcetypeassert, ginkgolinter, gochecknoglobals, gochecknoinits, goconst, gocritic, godot, godox, goerr113, goheader, gomnd, gomoddirectives, gomodguard, goprintffuncname, gosimple, grouper, importas, inamedparam, interfacebloat, ireturn, lll, loggercheck, makezero, mirror, misspell, musttag, nakedret, nilnil, nlreturn, nolintlint, nonamedreturns, nosprintfhostport, paralleltest, predeclared, promlinter, revive, sloglint, stylecheck, tagalign, tagliatelle, tenv, testpackage, thelper, tparallel, unconvert, usestdlibvars, varnamelen, wastedassign, whitespace, wrapcheck, wsl
test: exhaustruct, paralleltest, testableexamples, testifylint, testpackage, tparallel
unused: ineffassign, unparam, unused
在項目目錄的根目錄下通過golangci-lint run運行,即可進(jìn)行l(wèi)inters檢查,如果有問題,就會打印對應(yīng)的錯誤信息,記錄該問題所有上下文,包括問題的簡短描述,以及出現(xiàn)問題的文件和行號。
由于默認(rèn)不開啟gosec,所以只能掃描出一條:
golangci-lint run
main.go:23:21: Error return value of `http.ListenAndServe` is not checked (errcheck) http.ListenAndServe(":8080", nil)
golangci-lint的報告,默認(rèn)提供高亮顯示,對代碼行和標(biāo)記的標(biāo)識符都用不同顏色表示,可以方便快捷地獲得關(guān)鍵信息。
也可以指定文件和目錄檢查,其語法如下:
golangci-lint run cc1 dir2 dir3/test.go
配置
GolangCI-Lint可以針對不同用例提供靈活多樣的配置。可以通過命令行選項或配置文件進(jìn)行配置。注意命令行參數(shù)具有較高優(yōu)先級,覆蓋掉配置文件中的配置項目?;臼纠?#xff1a;
golangci-lint run --disable-all -E revive -E errcheck -E nilerr -E gosec
可以通過help linters當(dāng)前情況下預(yù)設(shè)的規(guī)則:
golangci-lint help linters | sed -n '/Linters presets:/,$p'
Linters presets:
bugs: asasalint, asciicheck, bidichk, bodyclose, contextcheck, durationcheck, errcheck, errchkjson, errorlint, exhaustive, exportloopref, gocheckcompilerdirectives, gochecksumtype, gosec, gosmopolitan, govet, loggercheck, makezero, musttag, nilerr, noctx, protogetter, reassign, rowserrcheck, sqlclosecheck, staticcheck, testifylint, zerologlint
comment: dupword, godot, godox, misspell
complexity: cyclop, funlen, gocognit, gocyclo, maintidx, nestif
error: errcheck, errorlint, goerr113, wrapcheck
format: decorder, gci, gofmt, gofumpt, goimports, sloglint, tagalign
import: depguard, gci, goimports, gomodguard
metalinter: gocritic, govet, revive, staticcheck
module: depguard, gomoddirectives, gomodguard
performance: bodyclose, noctx, perfsprint, prealloc
sql: execinquery, rowserrcheck, sqlclosecheck
style: asciicheck, containedctx, decorder, depguard, dogsled, dupl, errname, exhaustruct, forbidigo, forcetypeassert, ginkgolinter, gochecknoglobals, gochecknoinits, goconst, gocritic, godot, godox, goerr113, goheader, gomnd, gomoddirectives, gomodguard, goprintffuncname, gosimple, grouper, importas, inamedparam, interfacebloat, ireturn, lll, loggercheck, makezero, mirror, misspell, musttag, nakedret, nilnil, nlreturn, nolintlint, nonamedreturns, nosprintfhostport, paralleltest, predeclared, promlinter, revive, sloglint, stylecheck, tagalign, tagliatelle, tenv, testpackage, thelper, tparallel, unconvert, usestdlibvars, varnamelen, wastedassign, whitespace, wrapcheck, wsl
test: exhaustruct, paralleltest, testableexamples, testifylint, testpackage, tparallel
unused: ineffassign, unparam, unused
可以通過-p 或者-presetor標(biāo)志來運行預(yù)設(shè):
golangci-lint run -p bugs -p error
針對項目,可以通過項目配置來進(jìn)行預(yù)設(shè)配置特定的linter選項,而這是通過命令行選項無法實現(xiàn)的。配置文件格式可以支持yml、toml或json格式,為了方便建議使用yml格式,即.golangci.yml或.golangci.yaml文件。只需在項目目錄的根目錄中創(chuàng)建項目特定的配置。程序?qū)⒆詣釉谝獧z查的文件的目錄中查找它們,并在可以繼承查詢父目錄中的配置。一個典型的.golangci.yml配置如下(注意yml格式的縮進(jìn)):
linters:enable-all: truedisable:- maligned- preallocfast: false
配置解釋說明:
enable-all: true:這表示啟用所有可用的代碼檢查規(guī)則。當(dāng)設(shè)置為true時,將啟用所有代碼檢查規(guī)則,這意味著代碼檢查工具將檢查代碼中的所有問題。
disable:這是一個列出要禁用的具體代碼檢查規(guī)則的部分。在示例中,禁用了兩個規(guī)則:maligned 和 prealloc。這意味著代碼檢查工具不會檢查和報告與這兩個規(guī)則相關(guān)的問題。
fast: false:這是一個控制代碼檢查工具的速度和精度之間權(quán)衡的選項。如果設(shè)置為false,代碼檢查工具將更加準(zhǔn)確,但可能運行得較慢。如果設(shè)置為true,代碼檢查工具可能犧牲一些準(zhǔn)確性以提高速度。
可以明顯的看到配置了.golangci.yml 后,掃描結(jié)果明顯增多:
注釋忽略
有時針對個定的linting問題需要臨時忽略其顯示,可以通過nolint標(biāo)志或者配置文件中設(shè)置忽略項來說實現(xiàn)。
直接執(zhí)行g(shù)olangci-lint run -E gosec
linter規(guī)則中提示了一個 SQL 注入風(fēng)險 (G201: SQL string formatting)。
func searchHandler(w http.ResponseWriter, r *http.Request) {dealerId := r.URL.Query().Get("dealerId")if dealerId == "" {fmt.Fprint(w, "Please provide a search query.")return}table := fmt.Sprintf("risk_investigate_record a join (select max(I_ID) as MAX_ID from risk_investigate_record where ch_dealer_id ='%s' group by I_TOP_REF )b on a.I_ID = b.MAX_ID ", dealerId) //nolintrows, err := db.Query(table)if err != nil {fmt.Fprint(w, "An error occurred.")return}defer rows.Close()
}
通過由//nolint注釋,就可以告訴linting檢查器忽略對該行的檢查。也可以通過//nolint:xxx(比如gosec)忽略特定的linting檢查:
除了按照行來忽略,也支持通過代碼塊(比如函數(shù),{})來設(shè)置忽略:
//nolint
func aFunc() {
}
對整個源文件,可以通過在其開頭注釋,可以讓檢查器忽略對該文件的檢查:
//nolint:govet,errcheck
package main
排除規(guī)則
可以在配置文件中指定排除規(guī)則,以便更精細(xì)地控制哪些文件被檢查,以及報告哪些問題。例如,可以設(shè)置不檢查某些測試文件 (_test.go)上運行,或者禁止在項目范圍內(nèi)產(chǎn)生某些錯誤。