使用goland调试远程代码

简介

实际工作中难免遇到需要调试服务器上代码的情况,最近项目就遇到了代码在服务上报出tcp握手失败的异常,而本地却正常的情况,日志不好加,这里研究了一下golang的远程调试方法,并做记录。
测试基于goland和dlv实现go代码的远程调试。远程服务器采用centos7.9

go环境安装

安装配置
下载golang linux安装包,并解压到/root/apps/go 目录,配置环境变量

vi /etc/profile
export GOROOT=/root/apps/go
export GOPATH=/root/apps/go/gopath
export PATH=$PATH:/$GOROOT/bin:$GOPATH/bin

验证
执行 如下命令查看go的版本,能看到证明安装成功

[root@localhost go]# go version
go version go1.17.5 linux/amd64

dvl 工具安装

下载工具dlv

[root@localhost gopath]# go env -w GOPROXY=https://goproxy.cn  --配置golang代理
[root@localhost gopath]# cd $GOPATH -- 到 gopath目录下
[root@localhost gopath]# go install github.com/go-delve/delve/cmd/dlv@latest  --安装dlv
[root@localhost gopath]# ln -s $GOPATH/bin/dlv /usr/local/bin/dlv  --配置软连接
[root@localhost gopath]# dlv version
Delve Debugger
Version: 1.8.0
Build: $Id: 6a6c9c332d5354ddf1f8a2da3cc477bd18d2be53 $

dvl 工具启动

方式一 远端有项目源码时,保证远端和本地的项目代码一致即可项目文件夹根目录下使用如下命令

dlv debug --headless --listen=:2345 --api-version=2 --accept-multiclient

方式二 远端只有编译后的程序

  1.使用dlv运行程序:

dlv --listen=:2345 --headless=true --api-version=2 --accept-multiclient exec ./test001_linux

  带命令行参数,在可执行程序后面带上 --,再后面就是命令行参数:

dlv --listen=:2345 --headless=true --api-version=2 --accept-multiclient exec ./test001_linux -- -s 123

  2.先运行程序记住进程id,再运行dlv,具体如下

[root@localhost gopath]# nohup ./gotest  &
[2] 335
[root@localhost gopath]# nohup: 忽略输入并把输出追加到"nohup.out"

--注意 335 是 上述启动 go进程的id   2345 是服务监听的端口 这里写哪个端口 goland中就要配置哪个端口,其他参数可以通过 执行 dlv 查看帮助信息
[root@localhost gopath]# dlv attach 335 --headless --listen=:2345 --api-version=2 --accept-multiclient
API server listening at: [::]:2345
2021-12-26T13:06:55+08:00 warning layer=rpc Listening for remote connections (connections are not authenticated nor encrypted)

GoLand配置及启动

新建一个Go remote配置

然后在主机处输入服务器的ip地址,端口号使用默认的2345就行

 

 

posted @ 2022-08-24 17:42  落叶已飞  阅读(1143)  评论(0编辑  收藏  举报