VSCode中Go项目设置代码检查

在使用Goland时,它会及时对Go代码做一些检查。VSCode也可以,VSCodeGo插件会使用gopls工具进行检查,也可以手动配置检查工具比如流行的golangci-lint来进行检查。

1. 配置使用gopls工具及时检查

在项目.vscode/settings.json文件中或者用户的settings.json文件中配置ui.diagnostic.staticchecktrue即可及时使用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工具可以是staticcheckgolintgolangci-lintgolangci-lint-v2revive,默认是没有配置工具,这里建议配置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
        }
      }
    }
  ]
}

每次需要全项目检查时,手动运行此任务即可。

如果此文对你有帮助,欢迎点赞收藏!

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值