龙空技术网

golangci-line 工具介绍

Anthony-Dong 446

前言:

而今你们对“golang读取配置文件到静态类”都比较讲究,大家都需要了解一些“golang读取配置文件到静态类”的相关知识。那么小编在网络上搜集了一些有关“golang读取配置文件到静态类””的相关文章,希望大家能喜欢,小伙伴们快快来了解一下吧!

ci过程中,经常有一些可以通过静态分析或者白盒检测去避免一些问题以及规范代码格式!使用Go语言一般是使用golangci-line 作为代码检测工具!

1、安装

参考官网:

安装:curl-sSfL | sh -s -- -b $(go env GOPATH)/bin v1.43.0

版本信息:golangci-lint--version

目前我司是自己二开的 golangci-line,所以这里使用的开源版本,其实大同小异,就是开发了一些插件!

2、介绍

这个就是一个工具,集成了各类自动检测代码的工具,所以不需要本地安装太多的工具,只需要这个工具即可!

由于它需要一个go的项目,这里以我自己的项目去介绍, 项目地址:,如果有同学想自己尝试下可以直接下载我这个项目!项目也比较规范!

1、快速使用golangci-lint run--no-config 直接在项目目录下直接执行!使用--no-config的原因是我本地有配置文件!

➜  go-tool git:(master) golangci-lint run --no-configclear/clear.go:144:2: `Warnf` is unused (deadcode)    Warnf = func(format string, v ...interface{}) {    ^clear/clear.go:155:6: `Slice2String` is unused (deadcode)func Slice2String(body []byte) string {     ^clear/clear.go:284:6: `IgnoreParser` is unused (deadcode)type IgnoreParser interface {     ^clear/clear.go:398:6: `CompileIgnoreFile` is unused (deadcode)func CompileIgnoreFile(fpath string) (*GitIgnore, error) {     ^clear/clear.go:411:6: `CompileIgnoreFileAndLines` is unused (deadcode)func CompileIgnoreFileAndLines(fpath string, lines ...string) (*GitIgnore, error) {     ^command/wrk/metrics.go:11:2: `requestCount` is unused (deadcode)    requestCount = prometheus.NewCounter(prometheus.CounterOpts{    ^commons/internal/prettyjson/json.go:86:21: func `(*Formatter).sprintfColor` is unused (unused)func (f *Formatter) sprintfColor(c *color.Color, format string, args ...interface{}) string {                    ^commons/internal/unsafe/string.go:27:9: unsafeptr: possible misuse of reflect.SliceHeader (govet)    hdr := *(*reflect.SliceHeader)(unsafe.Pointer(&bytes))           ^commons/internal/unsafe/string.go:28:35: unsafeptr: possible misuse of reflect.StringHeader (govet)    return *(*string)(unsafe.Pointer(&reflect.StringHeader{                                     ^commons/internal/unsafe/string.go:35:9: unsafeptr: possible misuse of reflect.StringHeader (govet)    hdr := *(*reflect.StringHeader)(unsafe.Pointer(&str))           ^commons/internal/unsafe/string.go:36:35: unsafeptr: possible misuse of reflect.SliceHeader (govet)    return *(*[]byte)(unsafe.Pointer(&reflect.SliceHeader{                                     ^clear/clear.go:45:3: ineffectual assignment to allFile (ineffassign)        allFile = make([]string, 0)        ^
展示的格式可以通过命令切换,这个是文本展示,你可以使用golangci-lint run--no-config--out-format json 输出json,然后自己去做分析和前端ui展示!2、常用命令介绍

其实执行 golangci-lint run-h 就可以获取以下帮助

--build-tags go 语言编译的参数--timeout 整个检测时长--tests 是否检测test文件--no-config 不读取配置文件--skip-dirs-use-default 使用系统默认的忽略文件--disable-all 禁用全部插件--enable 开启插件--presets 开启插件(分类),目前看高版本好像看不到了具体的详情!--fix 开启自动修复

例如我经常使用的: 我日常就是开启format功能!

  golangci-lint run  --no-config --fix --skip-dirs-use-default \  --disable-all \  --enable gofmt \  --enable goimports \  --enable gci
3、插件工具

1、默认使用的插件

Enabled by default linters:deadcode: Finds unused code [fast: false, auto-fix: false]errcheck: Errcheck is a program for checking for unchecked errors in go programs. 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 a 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): Staticcheck is a go vet on steroids, applying a ton of static analysis checks [fast: false, auto-fix: false]structcheck: Finds unused struct fields [fast: false, auto-fix: false]typecheck: Like the front-end of a Go compiler, parses and type-checks Go code [fast: false, auto-fix: false]unused (megacheck): Checks Go code for unused constants, variables, functions and types [fast: false, auto-fix: false]varcheck: Finds unused global variables and constants [fast: false, auto-fix: false]

2、默认没用的

Disabled by default linters:asciicheck: Simple linter to check that your code does not contain non-ASCII identifiers [fast: true, auto-fix: false]bodyclose: checks whether HTTP response body is closed successfully [fast: false, auto-fix: false]cyclop: checks function and package cyclomatic complexity [fast: false, auto-fix: false]depguard: Go linter that checks if package imports are in a list of acceptable packages [fast: false, 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]durationcheck: check for two durations multiplied together [fast: false, auto-fix: false]errorlint: go-errorlint is a source code linter for Go software 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]exhaustive: check exhaustiveness of enum switch statements [fast: false, auto-fix: false]exhaustivestruct: Checks if all struct's 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: true, 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 control golang package import order and make it always deterministic. [fast: true, auto-fix: true]gochecknoglobals: check that no global variables exist [fast: true, auto-fix: false]gochecknoinits: Checks that no init functions are present in Go code [fast: true, 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 many 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: Golang 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: Goimports does everything that gofmt does. Additionally it checks unused imports [fast: true, auto-fix: true]golint: 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]ifshort: 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]interfacer: Linter that suggests narrower interface types [fast: false, auto-fix: false]lll: Reports long lines [fast: true, auto-fix: false]makezero: Finds slice declarations with non-zero initial length [fast: false, auto-fix: false]maligned: Tool to detect Go structs that would take less memory if their fields were sorted [fast: false, auto-fix: false]misspell: Finds commonly misspelled English words in comments [fast: true, auto-fix: true]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]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]paralleltest: paralleltest detects missing usage of t.Parallel() method in your Go test [fast: true, auto-fix: false]prealloc: Finds slice declarations that could potentially be preallocated [fast: true, auto-fix: false]predeclared: find code that shadows one of Go's predeclared identifiers [fast: true, 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: Scopelint checks for unpinned variables in go programs [fast: true, auto-fix: false]sqlclosecheck: Checks that sql.Rows and sql.Stmt are closed. [fast: false, auto-fix: false]stylecheck: Stylecheck is a replacement for golint [fast: false, auto-fix: false]testpackage: linter that makes you use a separate _test package [fast: true, auto-fix: false]thelper: thelper detects golang 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]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]

3、presets 分类:

Linters presets:bugs: asciicheck, bodyclose, durationcheck, errcheck, errorlint, exhaustive, exportloopref, gosec, govet, makezero, nilerr, noctx, rowserrcheck, scopelint, sqlclosecheck, staticcheck, typecheckcomment: godot, godox, misspellcomplexity: cyclop, funlen, gocognit, gocyclo, nestiferror: errcheck, errorlint, goerr113, wrapcheckformat: gci, gofmt, gofumpt, goimportsimport: depguard, gci, goimports, gomodguardmetalinter: gocritic, govet, revive, staticcheckmodule: depguard, gomoddirectives, gomodguardperformance: bodyclose, maligned, noctx, preallocsql: rowserrcheck, sqlclosecheckstyle: asciicheck, depguard, dogsled, dupl, exhaustivestruct, forbidigo, forcetypeassert, gochecknoglobals, gochecknoinits, goconst, gocritic, godot, godox, goerr113, goheader, golint, gomnd, gomoddirectives, gomodguard, goprintffuncname, gosimple, ifshort, importas, interfacer, lll, makezero, misspell, nakedret, nlreturn, nolintlint, paralleltest, predeclared, revive, stylecheck, testpackage, thelper, tparallel, unconvert, wastedassign, whitespace, wrapcheck, wsltest: exhaustivestruct, paralleltest, testpackage, tparallelunused: deadcode, ineffassign, structcheck, unparam, unused, varcheck
4. 常用的检测工具介绍gosimple 检测go的源代码,简化go的代码gci 主要是go 的import 进行ordergodot 主要是检测 go的文档是否是以. 结尾gofmt 和 go fmt 一样goimports 主要是修复 go 的 import ,比如你没有导入包errcheck 主要是检测函数抛出异常了,你没有捕获staticcheck 静态分析,类似于 govet5. golangci 配置文件

具体可以参考我的:

主要是做一些 无用代码检测,简化代码,格式化代码!然后执行 golangci-lint run --fix 即可

run:  # timeout for analysis, e.g. 30s, 5m, default is 1m  timeout: 1m  # exit code when at least one issue was found, default is 1  issues-exit-code: 1  # default is true. Enables skipping of directories:  #   vendor$, third_party$, testdata$, examples$, Godeps$, builtin$  skip-dirs-use-default: true # include `vendor` `third_party` `testdata` `examples` `Godeps` `builtin`  # which dirs to skip: issues from them won't be reported;  # can use regexp here: generated.*, regexp is applied on full path;  # default value is empty list, but default dirs are skipped independently  # from this option's value (see skip-dirs-use-default).  # "/" will be replaced by current OS file path separator to properly work  # on Windows.  skip-dirs:    - conf    - mock    - pb_gen    - rpc_gen    - thrift_gen  # which files to skip: they will be analyzed, but issues from them  # won't be reported. Default value is empty list, but there is  # no need to include all autogenerated files, we confidently recognize  # autogenerated files. If it's not please let us know.  # "/" will be replaced by current OS file path separator to properly work  # on Windows.  skip-files:    - ".*\\.my\\.go$"# output configuration optionsoutput:  # colored-line-number|line-number|json|tab|checkstyle|code-climate|junit-xml|github-actions  # default is "colored-line-number"  format: colored-line-number  # print lines of code with issue, default is true  print-issued-lines: true  # print linter name in the end of issue text, default is true  print-linter-name: true  # make issues output unique by line, default is true  uniq-by-line: true  # add a prefix to the output file references; default is no prefix  path-prefix: ""  # sorts results by: filepath, line and column  sort-results: falselinters:  disable-all: true # disable all linters, but left linters below  enable:    - bodyclose     # checks whether HTTP response body is closed successfully    - errcheck      # checking for unchecked errors in go programs    - staticcheck   # go vet on steroids, applying a ton of static analysis checks    - structcheck   # finds unused struct fields    - unparam       # finds unused function parameters    - goconst       # finds repeated strings that could be replaced by a constant    - gofmt         # checks whether code was gofmt-ed    - goimports     # does everything that gofmt does, additionally it checks unused imports    - gosimple      # for Go source code that specializes in simplifying a code    - dogsled       # for Go source code that specializes in simplifying a code    - exportloopref # checks for pointers to enclosing loop variables    - misspell      # finds commonly misspelled English words in comments    - gci           # control golang package import order and make it always deterministic    - godot         # checks if comments end in a period    # Recommended but not enabled by default.    # - godot             # checks if comments end in a period    # - errorlint         # finds code that will cause problems with the error wrapping scheme introduced in Go 1.13    # - maligned          # tool to detect Go structs that would take less memory if their fields were sorted    # - prealloc          # finds slice declarations that could potentially be preallocated    # - unconvert         # remove unnecessary type conversions    # Enable these linters as you need.    # - asciicheck        # checks that your code does not contain non-ASCII identifiers    # - depguard          # checks assignments with too many blank identifiers (e.g. x, _, _, _, := f())    # - dupl              # code clone detection    # - exhaustive        # checks exhaustiveness of enum switch statements    # - exhaustivestruct  # checks if all struct's fields are initialized    # - funlen            # tool for detection of long functions    # - gci               # control golang package import order and make it always deterministic    # - gochecknoglobals  # checks that no global variables exist    # - gochecknoinits    # checks that no init functions are present in Go code    # - godox             # tool for detection of    # - goerr113          # checks the errors handling expressions    # - gofumpt           # checks whether code was gofumpt-ed    # - goheader          # checks is file header matches to pattern    # - gomnd             # an analyzer to detect magic numbers.    # - goprintffuncname  # checks that printf-like functions are named with `f` at the end    # - gosec             # inspects source code for security problems    # - interfacer        # suggests narrower interface types    # - lll               # reports long lines    # - nakedret          # finds naked returns in functions greater than a specified function length    # - nestif            # reports deeply nested if statements    # - nlreturn          # checks for a new line before return and branch statements to increase code clarity    # - noctx             # noctx finds sending http request without context.Context    # - nolintlint        # reports ill-formed or insufficient nolint directives    # - rowserrcheck      # checks whether Err of rows is checked successfully    # - scopelint         # checks for unpinned variables in go programs    # - sqlclosecheck     # checks that sql.Rows and sql.Stmt are closed    # - testpackage       # linter that makes you use a separate _test package    # - tparallel         # tparallel detects inappropriate usage of t.Parallel() method in your Go test codes    # - whitespace        # tool for detection of leading and trailing whitespace    # - wrapcheck         # checks that errors returned from external packages are wrapped    # - wsl               # forces you to use empty lines    # Have replacement.    # - gomodguard        # => depcheck    # - stylecheck        # => bgolint    # - golint            # => bgolint#linters-settings:#  goimports:#  #issues:  exclude-use-default: true

标签: #golang读取配置文件到静态类