这是我参与「第五届青训营 」伴学笔记创作活动的第 7 天
自动重启工具 Air
大部分的文章都写的是热重载,官方也是,但我觉得说成是自动重启更合适
在编写程序时,需要频繁的重启测试,通过使用 Air 能自动监听文件改动,然后自动编译运行新的程序,这也是为什么说它不是一个热重载工具的原因
安装
go install github.com/cosmtrek/air@latest
使用
编写 .air.toml 文件
执行
air命令会自动在当前目录下查找.air.toml文件
# Config file for [Air](https://github.com/cosmtrek/air) in TOML format
# 工作目录
# . 或 绝对路径,请注意以下目录必须在 root 目录下
root = "."
tmp_dir = "_output/air_tmp"
[build]
# 构建执行的命令
cmd = "make build"
# 二进制文件位置,一般是 cmd 执行的产物
bin = "./_output/douyin-chat"
# 自定义二进制文件位置,可以在运行应用程序时设置环境变量
#full_bin = "APP_ENV=dev APP_USER=air ./tmp/main"
# 监听这些文件扩展名
include_ext = ["go"]
# Ignore these filename extensions or directories.
exclude_dir = ["_output"]
# 要监听的目录列表
#include_dir = ["dal", "handler", "model"]
# 要监听的文件
#include_file = ["main.go"]
# 排除文件列表
#exclude_file = []
# 排除文件的正则表达式列表
#exclude_regex = ["_test\\.go"]
# Exclude unchanged files.
exclude_unchanged = true
# Follow symlink for directories
follow_symlink = true
# 此日志文件名称位于 $(tmp_dir) 中
log = "air.log"
# It's not necessary to trigger build each time file changes if it's too frequent.
delay = 2000 # ms
# 发生构建错误时停止运行旧二进制文件
stop_on_error = true
# 杀死进程前发送中断信号(windows不支持此功能)
send_interrupt = false
# 发送中断信号后的延时
kill_delay = 500 # ms
# Rerun binary or not
rerun = false
# Delay after each executions
rerun_delay = 500
# 在运行二进制时添加额外的参数 (bin/full_bin)。 将运行 `$(bin/full_bin) hello world`。
args_bin = ["--debug", "--port=38300", "--log-pretty"]
[log]
# 显示日志时间
time = true
# 只显示主日志,隐藏 watcher、 build、 runner)
main_only = false
[color]
# 自定义每个部分的颜色。 如果未找到颜色,使用原始应用程序日志。
main = "magenta"
watcher = "cyan"
build = "yellow"
runner = "green"
[misc]
# 退出时删除 tmp 目录
clean_on_exit = false
需要重点关注的地方:
tmp_dir: 使用 air 会创建一个零时的文件夹,可以通过misc.clean_on_exit配置在中断 air 程序时自动删除该目录build.cmd: 每次重新编译时执行的命令build.bin: 每次运行的命令args_bin: 额外的命令参数
问题:
- tmp_dir 文件夹的创建需要保证父文件夹存在
- 使用像 Goland 这样的程序触发重启的频率较高,可以适当调高自动保存的时间