为什么需要实时加载?
之前使用Python编写Web项目的时候,常见的Flask或Django框架都是支持实时加载的,你修改了项目代码之后,程序能够自动重新加载并执行(live-reload),这在日常的开发阶段是十分方便的。
在使用Go语言的gin框架在本地做开发调试的时候,经常需要在变更代码之后频繁的按下Ctrl+C停止程序并重新编译再执行,这样就不是很方便。
Air介绍
怎样才能在基于gin框架开发时实现实时加载功能呢?像这种烦恼肯定不会只是你一个人的烦恼,所以我报着肯定有现成轮子的心态开始了全网大搜索。果不其然就在Github上找到了一个工具:Air。它支持以下特性:
|  | 彩色日志输出自定义构建或二进制命令
 支持忽略子目录
 启动后支持监听新目录
 更好的构建过程
 
 | 
安装air
Go
|  | go get -u github.com/cosmtrek/air
 | 
MacOS
Linux
Windows
使用Air
为了敲命令时更简单更方便,你应该把alias air=’~/.air’加到你的.bashrc或.zshrc中。
首先进入你的项目目录:
最简单的用法就是直接执行下面的命令:
|  | # 首先在当前目录下查找 `.air.conf`配置文件,如果找不到就使用默认的air -c .air.conf
 
 | 
推荐的使用方法是:
|  | # 1. 在当前目录创建一个新的配置文件.air.conftouch .air.conf
 
 # 2. 复制 `air.conf.example` 中的内容到这个文件,然后根据你的需要去修改它
 
 # 3. 使用你的配置运行 air, 如果文件名是 `.air.conf`,只需要执行 `air`。
 air
 
 | 
air_example.conf示例
完整的air_example.conf示例配置如下,可以根据自己的需要修改。
| 12
 3
 4
 5
 6
 7
 8
 9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 
 | 
 
 
 root = "."
 tmp_dir = "tmp"
 
 [build]
 
 cmd = "go build -o ./tmp/main ."
 
 bin = "tmp/main"
 
 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
 
 stop_on_error = true
 
 log = "air_errors.log"
 
 [log]
 
 time = true
 
 [color]
 
 main = "magenta"
 watcher = "cyan"
 build = "yellow"
 runner = "green"
 
 [misc]
 
 clean_on_exit = true
 
 | 
效果图
