gin开发之 Air实现热重载 | 青训营笔记

417 阅读2分钟

这是我参与「第五届青训营 」伴学笔记创作活动的第 3 天

为什么需要实时加载?

在使用Go语言的gin框架在本地做开发调试的时候,经常需要在变更代码之后频繁的按下Ctrl+C停止程序并重新编译再执行,这样就不是很方便。那么有没有一种方法可以让其程序在其运行时,如果更改代码可以让他直接自己更新并重新编译运行呢?

Air就是一个很好的中间件可以实现这个功能。

安装Air

通过在终端输入以下指令可以帮助我们进行导包。

go get -u github.com/cosmtrek/air

使用Air

为了方便使用,我们首先应该先进行软连接,使其更加方便的使用 ,即将alias air='~/.air'加到你的.bashrc.zshrc中。

具体方法如下

# 1. 在当前目录创建一个新的配置文件.air.conf
touch .air.conf

# 2. 复制 `air.conf.example` 中的内容到这个文件,然后根据你的需要去修改它

# 3. 使用你的配置运行 air, 如果文件名是 `.air.conf`,只需要执行 `air`。
air

这里提供一个基本模板来使用,具体的可以参考GitHub中的air官方文档 cosmtrek/air: ☁️ Live reload for Go apps (github.com)

# [Air](https://github.com/cosmtrek/air) TOML 格式的配置文件

# 工作目录
# 使用 . 或绝对路径,请注意 `tmp_dir` 目录必须在 `root` 目录下
root = "."
tmp_dir = "tmp"

[build]
# 只需要写你平常编译使用的shell命令。你也可以使用 `make`
# Windows平台示例: cmd = "go build -o tmp\main.exe ."
cmd = "go build -o ./tmp/main ."
# 由`cmd`命令得到的二进制文件名
# Windows平台示例:bin = "tmp\main.exe"
bin = "tmp/main"
# 自定义执行程序的命令,可以添加额外的编译标识例如添加 GIN_MODE=release
# Windows平台示例:full_bin = "tmp\main.exe"
full_bin = "APP_ENV=dev APP_USER=air ./tmp/main"
# 监听以下文件扩展名的文件.
include_ext = ["go", "tpl", "tmpl", "html"]
# 忽略这些文件扩展名或目录
exclude_dir = ["assets", "tmp", "vendor", "frontend/node_modules"]
# 监听以下指定目录的文件
include_dir = []
# 排除以下文件
exclude_file = []
# 如果文件更改过于频繁,则没有必要在每次更改时都触发构建。可以设置触发构建的延迟时间
delay = 1000 # ms
# 发生构建错误时,停止运行旧的二进制文件。
stop_on_error = true
# air的日志文件名,该日志文件放置在你的`tmp_dir`中
log = "air_errors.log"

[log]
# 显示日志时间
time = true

[color]
# 自定义每个部分显示的颜色。如果找不到颜色,使用原始的应用程序日志。
main = "magenta"
watcher = "cyan"
build = "yellow"
runner = "green"

[misc]
# 退出时删除tmp目录
clean_on_exit = true

之后便可以实现热重载了