Golang debug 推荐使用 Delve 工具,开源项目地址:
一、安装
1.开源方式安装
在src目录下执行如下命令
一、安装git clone
# git clone
# cd delve/cmd/dlv/
# go build
# go install
go build可能会如下报错:
根据报错提示,更改下目录即可:
2.go mod方式安装
go mod模式下推荐使用第二种方式,拉取最新 delve 项目代码到本地,编译安装。
# cd $GOPATH/src/
# git clone https:// github .com/go-delve/delve.git
# cd delve/cmd/dlv/
# go build
# go install
国内环境go build会报错:
go: golang.org/x/crypto@v0.0.0-20180614174826-fd5f17ee7299: unrecognized import path "golang.org/x/crypto" (https fetch: Get dial tcp 216.239.37.1:443: i/o timeout)
go: golang.org/x/sys@v0.0.0-20180614134839-8883426083c0: unrecognized import path "golang.org/x/sys" (https fetch: Get dial tcp 216.239.37.1:443: i/o timeout)
go: golang.org/x/arch@v0.0.0-20171004143515-077ac972c2e4: unrecognized import path "golang.org/x/arch" (https fetch: Get dial tcp 216.239.37.1:443: i/o timeout)
原因是 Golang 官网被墙了,这里手动修改go.mod文件,把项目地址替换为 github 上的地址,如:
# vim ../../go.mod
# 添加下面替换:
replace (
golang.org/x/arch v0.0.0-20171004143515-077ac972c2e4 => github.com/golang/arch v0.0.0-20171004143515-077ac972c2e4
golang.org/x/crypto v0.0.0-20180614174826-fd5f17ee7299 => github.com/golang/crypto v0.0.0-20180614174826-fd5f17ee7299
golang.org/x/sys v0.0.0-20180614134839-8883426083c0 => github.com/golang/sys v0.0.0-20180614134839-8883426083c0
)
然后重新编译安装,没有报错则成功。
3.添加$GOPATH/bin到 环境变量 ,执行dlv命令,查看:
二、使用 Delve 调试程序
1.查看 Delve 支持命令:dlv 或 dlv –help,如下:
Available Commands:
attach Attach to running process and begin debugging.
connect Connect to a headless debug server.
core Examine a core dump.
debug Compile and begin debugging main package in current directory, or the package specified.
exec Execute a precompiled binary, and begin a debug session.
help Help about any command
run Deprecated command. Use 'debug' instead.
test Compile test binary and begin debugging program.
trace Compile and begin tracing program.
version Prints version.
2.查询单个命令详情,dlv [command] –help,如:dlv debug –help
开启GO111MODULE:
# export GO111MODULE=on
3.调试程序手动创建一个 helloworld 项目,main.go里面打印一些信息,如:
package main
import "fmt"
func main() {
fmt.Println("hello world")
}
执行debug调试:
# cd helloword/
# go mod init
# dlv debug main.go
开启调试成功,执行help查看 debug 命令:
PS:
因为开启了go mod模式,所以 debug 前这里需要go mod init初始化 mod,不然会报错:
go: cannot find main module; see 'go help modules'
4.其他命令参数,自行调试。