在Linux环境下调试Golang代码,可以使用以下几种常用的调试工具:
Delve
go install github.com/go-delve/delve/cmd/dlv@latestdlv debug ./debug-demo(b)reak main.go:10(c)ontinue(n)ext 或 (s)tep(p)rint variableName(bt)GDB
sudo apt-get install gdbgo build -gcflags "-N -l" -o hello-world hello-world.gogdb ./hello-world(gdb) break main.go:5(gdb) run(gdb) next 或 (gdb) step(gdb) print variableName(gdb) quitGoland
pprof
net/http/pprof包,启动HTTP服务:import _ "net/http/pprof"
func main() {
go func() {
log.Println(http.ListenAndServe("localhost:6060", nil))
}()
// 你的程序代码
}
http://localhost:6060/debug/pprof/heap进行堆性能分析。http://localhost:6060/debug/pprof/profile进行CPU性能分析。Visual Studio Code (VSCode)
launch.json:{
"version": "0.2.0",
"configurations": [
{
"name": "Launch",
"type": "go",
"request": "launch",
"mode": "debug",
"program": "${fileDirname}",
"env": {},
"args": []
}
]
}
通过这些工具和方法,你可以在Linux环境下高效地调试Golang代码,选择合适的工具取决于你的具体需求和习惯。