Go 热编译与Debug方案 | Go主题月

1,795 阅读2分钟

前言

大家好,我是一名 PHPer 渣,至今还在撸 ThinkPHP 3.2,众所周知,在 PHP 是动态语言,开发环境实时响应,然后在 Go 这种静态语言,就很尴尬了!

作为初学者的我,有很长一段时间都在折腾这个 Go 热编译,然后除了百度,谷歌(英语渣,靠翻译),在微信等社交群聊查资料外,并无什么其他大佬指点和相关完整的解决方案,这让我走了很多弯路!!!

好了,废话不多说,直接进入主题,让你们看看如何实现 Go 热编译 + 实时 Debug

项目结构

.
├── .air.conf
├── makefile
├── cmd
│   └── serve
│      └── main.go # 这里有 Gin 逻辑
└── scripts
    └── run.sh

对,没错,就是这么简单!

环境配置

  • air 安装 https://github.com/cosmtrek/air
  • dlv 安装 https://github.com/go-delve/delve

PS: 安装不上请上机场

scripts/run.sh 文件

# 杀掉 air 进程,防止多次启动,杀掉之前运行的 air 进程
ps -ef | grep -w air | grep -v grep | sort -k 2rn | awk '{if (NR>1){print $2}}' | xargs kill -9
# 杀掉 serve 进程,这里的端口是 gin 运行的端口
lsof -i:8080 | grep serve | awk '{print $2}' | xargs kill -9
# 杀掉 dlv 进程,这里的端口是 dlv 运行的端口
lsof -i:2345 | grep dlv | awk '{print $2}' | xargs kill -9
# debug gin 项目
dlv debug --listen=:2345 --headless=true --api-version=2 --continue --accept-multiclient --output=./tmp/serve ./cmd/serve/main.go

makefile 文件

run-dev:
	ENV=dev ./scripts/run.sh

air.conf 文件

  • 主要套路 full_bin 配置,这里我们走 Makefile
# Config file for [Air](https://github.com/cosmtrek/air) in TOML format

# Working directory
# . or absolute path, please note that the directories following must be under root.
root = "."
tmp_dir = "./tmp"

[build]
# Just plain old shell command. You could use `make` as well.
cmd = "echo start build"

# Binary file yields from `cmd`.
# bin = "./tmp/main"

# Customize binary.
full_bin = "make run-dev"

# Watch these filename extensions.
include_ext = ["go", "yaml", "conf", "ttf"]

# Ignore these filename extensions or directories.
exclude_dir = ["tmp", "http"]

# Watch these directories if you specified.
include_dir = []

# Exclude files.
exclude_file = []

# Exclude unchanged files.
exclude_unchanged = true

# This log file places in your tmp_dir.
log = "air.log"

# It's not necessary to trigger build each time file changes if it's too frequent.
delay = 1000 # ms

# Stop running old binary when build errors occur.
stop_on_error = true

# Send Interrupt signal before killing process (windows does not support this feature)
send_interrupt = false

# Delay after sending Interrupt signal
kill_delay = 200 # ms

[log]
# Show log time
time = true

[color]
# Customize each part's color. If no color found, use the raw app log.
main = "magenta"
watcher = "cyan"
build = "yellow"
runner = "green"

[misc]
# Delete tmp directory on exit
clean_on_exit = true

最后,王炸

在项目目录终端下执行:air,即可成功热编译和实时 debug

附上项目地址

github.com/smithyj/yan…