在使用Goland时,它会及时对Go代码做一些检查。VSCode也可以,VSCode的Go插件会使用gopls工具进行检查,也可以手动配置检查工具比如流行的golangci-lint来进行检查。
1. 配置使用gopls工具及时检查
在项目.vscode/settings.json文件中或者用户的settings.json文件中配置ui.diagnostic.staticcheck为true即可及时使用staticcheck,它只是做一些基本的检查,不会像golangci-lint一样做深度检查。
staticcheck检查要求每个包有应该有一个注释并且包名不能有下划线,在实际项目中可能会打破这个规则,可以禁用这两个规则,可以在ui.diagnostic.analyses中配置禁用:
settings.json:
{
"gopls": {
"build.buildFlags": ["-tags=debug"], // 编译时添加`debug`标记
"ui.diagnostic.staticcheck": true, // 启用`staticcheck`检查
"ui.diagnostic.analyses": {
"ST1000": false, // 禁用规则`at least one file in a package should have a package comment`
"ST1003": false // 禁用规则`should not use underscores in package names`
}
},
}
2. 配置golangci-lint检查
在go插件中本身有Lint检查,可以检查当前包,也可以检查整个项目:

在Go扩展的设置中可以配置Lint On Save以及Lint Tool,保存时可以Lint检查文件,包或者整个项目;Lint工具可以是staticcheck、golint、golangci-lint、golangci-lint-v2、revive,默认是没有配置工具,这里建议配置golangci-lint-v2。

但是有一个问题就是,到目前为止golangci-lint-v2,都不支持go.work,即如下目录结构:
.
├── app
│ └── go.mod
├── deps
│ └── go.mod
└── go.work
在项目根目录运行时会报错:[error] level=error msg="[linters_context] typechecking error: pattern ./...: directory prefix . does not contain modules listed in go.work or their selected dependencies"

为此我们可以配置一个VSCode任务,在task.json中配置:
{
// See https://go.microsoft.com/fwlink/?LinkId=733558
// for the documentation about the tasks.json format
"version": "2.0.0",
"tasks": [
{
"label": "linter",
"type": "shell",
"command": "golangci-lint-v2.exe run",
"args": [
"--issues-exit-code=0",
"--output.text.print-issued-lines=false",
"--show-stats=false",
"--output.text.path=stdout",
"--path-mode=abs",
"./app/..."
],
"options": {
"cwd": "${workspaceFolder}"
},
"group": {
"kind": "build",
"isDefault": true
},
"problemMatcher": {
"owner": "go-lint",
"source": "go-golangci-lint-v2",
"fileLocation": ["autoDetect", "${workspaceFolder}"],
"pattern": {
"regexp": "^(.*?):(\\d+):(\\d+):\\s+(.*)$",
"file": 1,
"line": 2,
"column": 3,
"message": 4
}
}
}
]
}
每次需要全项目检查时,手动运行此任务即可。
如果此文对你有帮助,欢迎点赞收藏!

3万+

被折叠的 条评论
为什么被折叠?



