简介
air是 Go 语言的热加载工具,它可以监听文件或目录的变化,自动编译,重启程序。大大提高开发期的工作效率。
快速使用
本文代码使用 Go Modules,在 Mac 上运行。
先创建目录并初始化:
$ mkdir air && cd air$ go mod init github.com/go-quiz/go-daily-lib/air
执行下面的命令安装air工具:
$ go get -u github.com/cosmtrek/air
上面的命令会在$GOPATH/bin目录下生成air命令。我一般会将$GOPATH/bin加入系统PATH中,所以可以方便地在任何地方执行air命令。
下面我们使用标准库net/http编写一个简单的 Web 服务器:
package mainimport ("fmt""log""net/http")func index(w http.ResponseWriter, r *http.Request) {fmt.Fprintln(w, "Hello, world!")}func main() {mux := http.NewServeMux()mux.HandleFunc("/", index)server := &http.Server{Handler: mux,Addr: ":8080",}log.Fatal(server.ListenAndServe())}
运行程序:
$ go run main.go
在浏览器中访问localhost:8080即可看到Hello, world!。
如果现在要求把Hello, world!改为Hello, dj!,如果不用air只能修改代码,执行go build编译,然后重启。
使用air,我们只需要执行下面的命令就可以运行程序:
$ air
air会自动编译,启动程序,并监听当前目录中的文件修改:

当我们将Hello, world!改为Hello, dj!时,air监听到了这个修改,会自动编译,并且重启程序:

这时,我们在浏览器中访问localhost:8080,文本会变为Hello, dj!,是不是很方便?
配置
直接执行air命令,使用的就是默认的配置。一般建议将air项目中提供的air_example.toml配置文件复制一份,根据自己的需求做修改和定制:
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 = []log = "air.log"delay = 1000 # msstop_on_error = truesend_interrupt = falsekill_delay = 500 # ms[log]time = false[color]main = "magenta"watcher = "cyan"build = "yellow"runner = "green"[misc]clean_on_exit = true
可以配置项目根目录,临时文件目录,编译和执行的命令,监听文件目录,监听后缀名,甚至控制台日志颜色都可以配置。
调试模式
如果想查看air更详细的执行流程,可以使用-d选项。

使用-d选项,air会输出非常详细的信息,可以帮助排查问题。
总结
在开发期,使用air可以避免频繁地编译,重启。把这些都自动化了,大大地提升了开发效率。
大家如果发现好玩、好用的 Go 语言库,欢迎到 Go 每日一库 GitHub 上提交 issue😄
参考
- air GitHub:https://github.com/cosmtrek/air
- Go 每日一库 GitHub:https://github.com/go-quiz/go-daily-lib
