### delve
开源项目地址https://github.com/go-delve/delve.
提供golang调试可以debug和attach.
安装使用go get, 同时将gopath添加进入环境变量以便于能够运行dlv工具.
go get -u github.com/go-delve/delve/cmd/dlv
### 调试例子
test.go
```
package test
var Test_val int = 2000
```
main.go
```
package main
import (
"dlv/test"
"fmt"
"log"
"net/http"
"os"
)
const port = "8000"
func main() {
log.Println("main")
http.HandleFunc("/hi", hi)
fmt.Println("runing on port: " + port)
log.Fatal(http.ListenAndServe(":"+port, nil))
}
func hi(w http.ResponseWriter, r *http.Request) {
hostName, _ := os.Hostname()
testSet := 1000
log.Println(testSet, test.Test_val)
fmt.Fprintf(w, "HostName: %s", hostName)
}
```
### debug调试
启动调试:
dlv debug main.go
设置断点: b filename:fucname or filename:linenum根据行号或者函数名字添加断点
b main.main 根据函数名设置断点
b main.go:24 根据行数设置断点
查看断点:bp
条件断点:cond 2 testSet == 1000
开始运行:c
浏览器中访问:localhost:8000/hi会自动断点到24行
显示参数:args
局部变量: locals
显示变量: p hostName
显示全局:vars test.Test_val
修改变量:set testSet = 5000
继续执行:c
单行执行:n
单步执行:s
跳出函数:so
显示代码:l
删除断点:clear 1
清除断点:clear all
显示stack: stack
选择栈帧:frame 1
查看协程:gr
所有协程:grs
所有线程:threads
指定线程:thread id
### 编译选项
go build -gcflags "-N -l"
### attach调试
编译运行,查找进程id,attach进程
go build main.go
main
ps -aux | grep main
dlv attach pid
### 远程调试
如何远程调golang程序,当要调试服务器上的golang代码时有两种方式,在服务器本地调试,在本地远程调试。
1. 登录server上安装好golang环境和dlv
2. 获取调试服务器的PID, eg:ps -aux | grep main
3. 启动调试服务器dlv attach 7148 --headless --listen=:2345 --api-version=2 --accept-multiclient
4. 本地连接服务器进行调试:dlv connect 127.0.0.1:2345
### vscode调试环境搭建
1. 安装Go for Visual Studio Code 插件Rich Go language support for Visual Studio Code
2. 设置扩展: "go.gopath": "D:\\gopath", "go.goroot": "C:\\Go"
3. 运行命令面板执行Go:Install/Update Tool 勾选所有的的插件进行安装
### vscode调试配置
```
{
// 使用 IntelliSense 了解相关属性。
// 悬停以查看现有属性的描述。
// 欲了解更多信息,请访问: https://go.microsoft.com/fwlink/?linkid=830387
"version": "0.2.0",
"configurations": [
{
"name": "Connect to server",
"type": "go",
"request": "attach",
"mode": "remote",
"remotePath": "${workspaceFolder}",
"port": 2345,
"host": "127.0.0.1",
"showLog": true
},
{
"name": "Attach to Process",
"type": "go",
"request": "attach",
"mode": "local",
"processId": 22696
},
{
"name": "Launch Package",
"type": "go",
"request": "launch",
"mode": "debug",
"program": "${workspaceFolder}"
},
{
"name": "Launch file",
"type": "go",
"request": "launch",
"mode": "debug",
"program": "${file}"
}
]
}
```
上面配置包含启动调试、attach、remote调试四种模式
有疑问加站长微信联系(非本文作者))