【导读】go 语言静态检查工具 go lint 是什么?如何使用?本文详细介绍了 go lint。
静态代码分析。通俗地讲,扫描源代码,在不运行代码的情况下,找出一些不规范的书写方式以修正,
例如:if foo != false {...}
这样的写法显然不如 if foo {}
好理解。
lint 程序扫描到这样的case就可以给出提示,敦促开发者修正。下面是一些lint能检测到的问题样例:
fmt.Sprintf("%d", "123") // 错误
fmt.Sprintf("%s", "123") // 正确
for i, _ := range []int{1,2,3}{} // 错误
for i := range []int{1,2,3}{} // 正确
a := make([]int, 0, 0) // 错误
a := make([]int, 0) // 正确
for _, v := range vs { // 错误
vectors = append(vectors, v)
}
vectors = append(vectors, vs...) // 正确
背景: 团队代码库,因为历史遗留小问题很多,肉眼排查不实际,想到引入lint解决该问题。
**ci工具选择:**linter如上介绍使用Golangci-lint。我们公司使用Gitlab作为源码管理平台,ci工具使用它提供的 Gitlabci。
下面是我自己做的准备工作,
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
2. 配置Golangci-lint
在项目根目录下创建文件.golangci.yml
,这个文件是golangci-lint的配置文件,可自定义 开启/关闭哪些linter
、跳过某些文件
、跳过某些lint规则
等。
如无配置文件,Golangci-lint会开启一些预设linter,这些在其文档内有说明。
下面是我们组一个项目现在的.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
3. 运行linter/修正错误
在项目根目录下运行golangci-lint run
,
该命令会加载.golangci.yml
(如有),执行lint。如代码有问题,命令行会输出错误提示,包括犯错地点、修正方法,有时linter提示会比较含糊,拿关键字google一下能找到详细说明
4. 推广
为做到平滑的推广lint,在操作时有下面的实践
deadcode
,unused
,之后开启规则更严格的linter例如gosimple
。以使同事逐渐适应。5. **与gitlabci集成,**走到这里lint工具的准备就ok了,下面要将它和ci工具衔接在一起,
.gitlab-ci.yml
的配置文件,这样每当push代码时,gitlab检测到有该文件,就会触发runner执行ci。我的.gitlab-ci.yml
文件内容如下image: registry.company.cn/ee/go:1.12.9-4
stages:
- qa
lint:
stage: qa
script:
- golangci-lint runGitLab CI/CD | GitLabimage: registry.company.cn/ee/go:1.12.9-4
stages:
- qa
lint:
stage: qa
script:
- golangci-lint run
转自:夏路
zhuanlan.zhihu.com/p/143567949
- EOF -
Go 开发大全
参与维护一个非常全面的Go开源技术资源库。日常分享 Go, 云原生、k8s、Docker和微服务方面的技术文章和行业动态。
关注后获取
回复 Go 获取6万star的Go资源库
分享、点赞和在看
支持我们分享更多好文章,谢谢!