Go热重载需借助第三方工具实现,常用方案有:1. air(最流行,配置灵活);2. fresh(轻量免配);3. inotifywait脚本(Linux简易方案);推荐使用air并纳入版本控制。

在Go语言开发中,热重载(Hot Reload)能显著提升开发效率。它能在代码保存后自动重新编译并重启服务,无需手动操作。虽然Go本身不自带热重载功能,但可以通过第三方工具轻松实现。以下是常用热重载工具的配置与使用方法。
1. 使用 air 工具实现热重载
air 是目前最流行的 Go 热重载工具之一,安装简单,配置灵活,支持自定义构建和运行命令。
步骤如下:
- 安装 air:
go install github.com/cosmtrek/air@latest - 确保 $GOPATH/bin 已加入系统 PATH,否则可能无法执行 air 命令
- 在项目根目录下生成默认配置文件:
air init - 修改生成的 .air.toml 文件以适配项目需求,例如指定监听目录、忽略文件、构建命令等
示例 .air.toml 配置:
立即学习“go语言免费学习笔记(深入)”;
root = "." tmp_dir = "tmp" [build] args_bin = "./tmp/main" bin = "tmp/main" cmd = "go build -o ./tmp/main ." delay = 1000 exclude_dir = ["assets", "tmp", "vendor"] exclude_file = [] exclude_regex = ["_test\\.go"] exclude_unchanged = false follow_symlink = false full_bin = "" include_ext = ["go", "tpl", "tmpl", "html"] include_file = [] kill_delay = "0s" log = "stdout" [log] main_only = false time = false [color] main = "magenta" [misc] clean_on_exit = true
启动热重载:
air2. 使用 fresh 工具快速启动
fresh 是另一个轻量级热重载工具,适合快速项目接入。
- 安装 fresh:
go install github.com/pilu/fresh@latest - 进入项目目录并运行:
fresh
fresh 默认会查找 main.go 并监听当前目录下的 .go 文件变化,自动重新编译运行,无需额外配置。
3. 简单场景:使用 shell 脚本 + inotifywait
在 Linux 环境下,可结合 inotify-tools 实现简易热重载。
- 安装 inotify-tools(Ubuntu/Debian):
sudo apt-get install inotify-tools - 编写监控脚本 monitor.sh:
#!/bin/bash while inotifywait -r -e modify,create,delete .; do go run main.go done
- 赋予执行权限并运行:
chmod +x monitor.sh && ./monitor.sh
4. 推荐配置建议
- 推荐使用 air,功能完整且社区活跃,支持 Windows、macOS、Linux
- 将 .air.toml 加入版本控制,便于团队统一开发环境
- 在 .air.toml 中合理设置 exclude_dir 和 include_ext,避免频繁触发重建
- 配合 IDE 保存时格式化代码,热重载能立即反映最终效果
基本上就这些。选择合适的热重载工具,能让你专注编码,不再频繁手动重启服务。










