golangci-lint使用

背景:下面的實踐是在golang 1.19版本下進行的

什么是lint

lint是用來進行代碼的靜態(tài)分析工具。既在不運行代碼的前提下,找出代碼中不規(guī)范以及存在bug的地方。存在各種各樣的lint

golangci-lint

golangci-lint提供了豐富的linter框架,通過配置可以選擇開啟或關(guān)閉特定的linter。

實踐

  1. 安裝
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
  1. 配置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
  1. 配置vscode(可選)
    參考:https://itcn.blog/p/3347295113.html,主要是開啟golint配置

  2. 使用
    運行下面命令,即可進行檢查代碼。此命令會檢查當(dāng)前目錄下的.golangci.yml文件,然后輸出結(jié)果

golangci-lint run
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容