[译] 使用 VSCode 调试 Golang
原文来自于: vscode-go
安装 Delve
有两种安装 Delve 的方式:
Go: Install/Update Toolsdlv
VS Code 命令面板查看命令面板
调试器配置说明
调试器会使用要以下这些配置, 在通常情况下, 你不需要更改或者修改他们中的任何一项, 但是需要看一看。
go.gopathgo.inferGopathgo.delveConfigapiVersiondlvLoadConfigmaxStringLenmaxArrayValuesmaxStructFields-1maxVariableRecurse
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 中调试参考:github.com/lukehoban/w…
一步一步调试

Troubleshooting
Go: Install/Update ToolsdlvOK
启动调试日志
showLogtruetraceloglogOutputrpclogOutputdelve--log-output
相关资料
更多原创文章干货分享,请关注公众号
- 加微信实战群请加微信(注明:实战群):gocnio