golangci-lint使用

背景:下面的实践是在golang 1.19版本下进行的

什么是lint

lint是用来进行代码的静态分析工具。既在不运行代码的前提下,找出代码中不规范以及存在bug的地方。存在各种各样的lint

golangci-lint

golangci-lint提供了丰富的linter框架,通过配置可以选择开启或关闭特定的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文件,文件内容如下:
linters:
  disable-all: true  # 关闭其他linter
  enable:            # 下面是开启的linter列表,之后的英文注释介绍了相应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,我们手动开启了它的某些扫描规则
    check-shadowing: true
    check-unreachable: true
    check-rangeloops: true
    check-copylocks: true
  1. 配置vscode(可选)
    参考:https://itcn.blog/p/3347295113.html,主要是开启golint配置

  2. 使用
    运行下面命令,即可进行检查代码。此命令会检查当前目录下的.golangci.yml文件,然后输出结果

golangci-lint run

你可能感兴趣的:(golangci-lint使用)