Delve是Go语言官方推出的调试工具,深度支持Go特性(如goroutine、接口等),是Linux下调试Golang的首选工具。
go install命令安装最新版本,并确保$GOPATH/bin在$PATH环境变量中(方便全局调用)。go install github.com/go-delve/delve/cmd/dlv@latest
-gcflags="-N -l"禁用编译器优化和内联(否则断点可能无法准确定位)。go build -gcflags="-N -l" -o debug-program main.go
dlv命令启动调试,支持直接调试可执行文件或源码。dlv debug ./debug-program # 调试源码
dlv exec ./debug-program # 调试编译后的可执行文件
break <文件名>:<行号>:设置断点(如break main.go:10);continue(或c):继续执行程序,直到下一个断点;next(或n):执行下一行代码(不进入函数);step(或s):进入当前行的函数内部;print <变量名>(或p):查看变量值(如print user.Name);set <变量名> <值>:修改变量值(如set user.Age 30);quit(或q):退出调试会话。pprof是Go的标准性能分析工具,用于定位CPU、内存、goroutine等性能瓶颈。
net/http/pprof包,并启动HTTP服务器(通常监听localhost:6060)。import _ "net/http/pprof"
func main() {
go func() {
log.Println(http.ListenAndServe("localhost:6060", nil))
}()
// 业务逻辑代码
}
# 收集30秒CPU数据
curl http://localhost:6060/debug/pprof/profile?seconds=30 > cpu.pprof
# 收集内存分配数据
curl http://localhost:6060/debug/pprof/heap > heap.pprof
# 查看goroutine堆栈
curl http://localhost:6060/debug/pprof/goroutine > goroutine.pprof
go tool pprof命令分析数据,支持文本模式或可视化模式(如web命令生成调用图)。go tool pprof cpu.pprof # 分析CPU数据
go tool pprof -http=:8080 cpu.pprof # 可视化分析(需web环境)
VS Code是轻量级编辑器,通过安装Go扩展(如golang.go)可实现图形化调试,适合新手或偏好可视化操作的用户。
GOPATH、GOROOT)。Ctrl+Shift+D);debug)。{
"version": "0.2.0",
"configurations": [
{
"name": "Launch Program",
"type": "go",
"request": "launch",
"mode": "debug",
"program": "${fileDirname}", // 当前目录
"args": ["--param=value"], // 可选:传递命令行参数
"env": {} // 可选:环境变量
}
]
}
F5),程序会在断点处暂停,通过调试工具栏控制执行(继续、单步、进入等),并查看变量、调用堆栈等信息。Goland是JetBrains推出的专业Go IDE,内置强大的调试功能,适合大型项目或团队协作。
File→Project Structure→SDKs添加)。log或fmt包在关键位置打印变量值和执行流程(如log.Println("Current user:", user)),帮助快速定位问题。if err != nil { log.Fatal(err) }),使用errors.Is和errors.As处理特定错误类型(Go 1.13+)。defer语句确保资源释放(如关闭文件、数据库连接),避免资源泄漏。