Air
Air
是一个用于 Go 项目的热加载工具,能够在代码变动时自动编译并重启程序,从而极大地提高开发效率。下面是 Air
的使用方法:
1. 安装 Air
你可以通过以下命令来安装 Air
:
curl -fLo air https://raw.githubusercontent.com/cosmtrek/air/master/install.sh && chmod +x air && mv air /usr/local/bin/
或者使用 Go 来安装:
go install github.com/cosmtrek/air@latest
2. 配置 Air
Air
会自动检测项目中的 .air.toml
配置文件。如果你的项目中没有该文件,你可以通过以下命令生成默认的配置文件:
air init
生成的 .air.toml
文件会包含如下配置项:
root = "."
testdata_dir = "testdata"
tmp_dir = "tmp"
[build]
args_bin = []
bin = "tmp\\main.exe"
cmd = "go build -o ./tmp/main.exe ."
delay = 1000
exclude_dir = ["assets", "tmp", "vendor", "testdata"]
exclude_file = []
exclude_regex = ["_test.go"]
exclude_unchanged = false
follow_symlink = false
full_bin = ""
include_dir = []
include_ext = ["go", "tpl", "tmpl", "html"]
include_file = []
kill_delay = "0s"
log = "build-errors.log"
poll = false
poll_interval = 0
post_cmd = []
pre_cmd = []
rerun = false
rerun_delay = 500
send_interrupt = false
stop_on_error = false
[color]
app = ""
build = "yellow"
main = "magenta"
runner = "green"
watcher = "cyan"
[log]
main_only = false
time = false
[misc]
clean_on_exit = false
[proxy]
app_port = 0
enabled = false
proxy_port = 0
[screen]
clear_on_rebuild = false
keep_scroll = true
你可以根据需要修改 .air.toml
文件。例如,你可以指定需要监控的文件夹、忽略的文件夹、构建参数等。
3. 运行 Air
完成配置后,使用以下命令启动 Air
:
air
当代码文件发生变化时,Air
会自动编译并重启程序。你会在终端中看到类似如下的输出:
watching .
! Main program running...
4. 实时查看文件变化
Air
会持续监控项目文件夹的变化,并在发生变动时重新编译和运行项目,无需手动重启服务器或重新运行命令。
主要优势:
- 自动重启:在每次代码变动时自动编译和重启应用程序。
- 灵活的配置:通过
.air.toml
文件,你可以自定义监控哪些目录、忽略哪些文件等。 - 提高开发效率:减少频繁手动重启程序的操作,尤其适合 Web 开发。
详细文档可以访问 Air 官方 GitHub 仓库