本文字数:2100字
阅读时间:10分钟

安装 Delve
有两种安装 Delve 的方式:
Go: Install/Update Toolsdlv
查看命令面板
调试器配置说明
调试器会使用要以下这些配置, 在通常情况下, 你不需要更改或者修改他们中的任何一项, 但是需要看一看。
go.gopathgo.inferGopathgo.delveConfigmaxStringLenmaxArrayValuesmaxStructFields-1maxVariableRecurseapiVersiondlvLoadConfig
delve
在调试视图中检查变量时,可能需要更改字符串和数组的长度, 默认上限更改为 64。
在调试视图中检查嵌套变量时,请按照实际情况进行配置。
launch.json
Debug: Open launch.jsonlaunch.json
{"version": "0.2.0","configurations": [{"name": "Launch","type": "go","request": "launch","mode": "auto","program": "${fileDirname}","env": {},"args": []}]}
launch.json
golaunchattachattachlaunchlaunchautodebugremotetestexecattachlocalremote{ "ENVNAME": "ENVVALUE" }envenvFiletruedebuggergdbwirelldboutdebuglineerrrpcshowLogtruemoderemote
在调试过程中使用 VS Code 变量
${workspaceFolder} ${file}${fileDirname}
使用 build tags
go build -tags=whatever_tagbuildFlags"-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"
]
}
调试包内所有测试用例配置样本
{
"name": "Launch test package",
"type": "go",
"request": "launch",
"mode": "test",
"program": "${workspaceFolder}"
}
调试预构建二进制配置样本
{
"name": "Launch executable",
"type": "go",
"request": "launch",
"mode": "exec",
"program": "absolute-path-to-the-executable"
}
调试本地已运行进程配置样本
{
"name": "Attach to local process",
"type": "go",
"request": "attach",
"mode": "local",
"processId": 0
}
远程调试
要使用 VS Code 进行远程调试, 那么需要在远程服务器上运行 headless delve 服务。下面这个示例假定了 你要调试的程序与你在同一目录下, 如果没有, 请参考 dlv debug 命令上的用法文档。
# 在远程服务器上启动 delve 服务
$ dlv debug --headless --listen=:2345 --log --api-version=2
Delve
$ dlv debug --headless --listen=:2345 --log -- -myArg=123
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": 2345, # 目标端口"program": "absolute-path-to-the-file-on-the-local-machine","env": {}}
remotePathprogramremotePath
Launch remotedlv
在 Docker 中调试参考:https://github.com/lukehoban/webapp-go/tree/debugg...
一步一步调试

Troubleshooting
Go: Install/Update ToolsdlvOK
启动调试日志
showLogtruetraceloglogOutputrpclogOutputdelve--log-output
相关资料
一步一步 debug: https://code.visualstudio.com/docs/editor/debuggin...

点击