能进行调试肯定go的环境没问题,调试依赖dlv,自行安装,还有我们调试的时候需要以main.go文件为入口
设置launch.json配置文件
当 delve 安装后, 运行命令Debug: Open launch.json, 如果没有 launch.json 文件, 则会使用默认配置创建一个文件,此文件用于调试当前程序。
{
"version": "0.2.0",
"configurations": [
{
"name": "Launch",
"type": "go",
"request": "launch",
"mode": "auto",
"program": "${fileDirname}",
"env": {},
"args": []
}
]
}
以下是launch.json中的一些属性说明:
| 属性 | 说明 |
|---|---|
| name | 定义配置名字 |
| type | 指定语言,这里我们填go即可 |
| request | launch ,attach, 当需要对一个已经运行的的程序 debug 时才使用 attach,其他时候使用launch |
| mode | 对于 launch 有 auto, debug, remote, test, exec, 对于 attach只有local,remote |
| program | 指定包, 文件或者是二进制的绝对路径 |
| env | 调试程序时需要注入的环境变量, 例如:{ "ENVNAME": "ENVVALUE" } |
| envFile | 绝对路径,env的值会覆盖envFile的值 |
| args | 需要传给调试程序的命令行参数 |
| showLog | 布尔值,是否在调试控制台打印日志, 一般为true |
| logOutput | 日志输出目标, 使用逗号分隔达到使用多个组件输出日志的目的 (debugger, gdbwire, lldbout, debuglineerr, rpc), 当 showLog 为 true 有效 |
| buildFlags | 构建程序时需要传递给 Go 编译器的 Flags |
| remotePath | 如果mode为remote时, 需要指定调试文件所在服务器的绝对路径 |
| processId | 进程 id |
| host | 目标服务器地址 |
| port | 目标端口 |
在调试过程中使用 VS Code 变量
${workspaceFolder}在工作区的的根目录调试程序${file}调试当前文件${fileDirname}调试当前文件所属的程序包
使用 build tags
如果在构建时需要构建标签, (比如:go build -tags=whatever_tag ), 则需要使用标签buildFlags 并添加内容: "-tags=whatever_tag" ,如果你需要使用多个标签时, 则需要使用单引号引起来,像这样:"-tags='first_tag second_tag third_tag'"
常用的launch.json 配置示例
在编辑launch.json时, 你可以将下面这些代码片段用于调试配置。
调试当前文件的配置样本
{
"name": "Launch file",
"type": "go",
"request": "launch",
"mode": "auto",
"program": "${file}"
}
调试单个测试用例配置样本
{
"name": "Launch test function",
"type": "go",
"request": "launch",
"mode": "test",
"program": "${workspaceFolder}",
"args": [
"-test.run",
"MyTestFunction"
]
}
# 在远程服务器上启动 delve 服务
$ dlv debug --headless --listen=:8888 --log --api-version=2
如果需要传递参数到程序, 必须通过Delve 服务传递,例如:
$ dlv debug --headless --listen=:8888 --log -- -myArg=123
然后在 VS Code 中创建一个远程调试的launch.json
{
"name": "Launch remote",
"type": "go",
"request": "launch",
"mode": "remote",
"remotePath": "absolute-path-to-the-file-being-debugged-on-the-remote-machine",
"host": "127.0.0.1", # 目标服务器地址
"port": 8888, # 目标端口
"program": "absolute-path-to-the-file-on-the-local-machine",
"env": {}
}
remotePath应该指向目标服务器中调试文件的绝对路径 (在源代码中)program指向本地计算机上文件的绝对路径,此路径与remotePath对应。