简介

air是 Go 语言的热加载工具,它可以监听文件或目录的变化,自动编译,重启程序。大大提高开发期的工作效率。

快速使用

本文代码使用 Go Modules,在 Mac 上运行。

先创建目录并初始化:

  1. $ mkdir air && cd air
  2. $ go mod init github.com/go-quiz/go-daily-lib/air

执行下面的命令安装air工具:

  1. $ go get -u github.com/cosmtrek/air

上面的命令会在$GOPATH/bin目录下生成air命令。我一般会将$GOPATH/bin加入系统PATH中,所以可以方便地在任何地方执行air命令。

下面我们使用标准库net/http编写一个简单的 Web 服务器:

  1. package main
  2. import (
  3. "fmt"
  4. "log"
  5. "net/http"
  6. )
  7. func index(w http.ResponseWriter, r *http.Request) {
  8. fmt.Fprintln(w, "Hello, world!")
  9. }
  10. func main() {
  11. mux := http.NewServeMux()
  12. mux.HandleFunc("/", index)
  13. server := &http.Server{
  14. Handler: mux,
  15. Addr: ":8080",
  16. }
  17. log.Fatal(server.ListenAndServe())
  18. }

运行程序:

  1. $ go run main.go

在浏览器中访问localhost:8080即可看到Hello, world!

如果现在要求把Hello, world!改为Hello, dj!,如果不用air只能修改代码,执行go build编译,然后重启。

使用air,我们只需要执行下面的命令就可以运行程序:

  1. $ air

air会自动编译,启动程序,并监听当前目录中的文件修改:

每日一库之56:air - 图1

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

每日一库之56:air - 图2

这时,我们在浏览器中访问localhost:8080,文本会变为Hello, dj!,是不是很方便?

配置

直接执行air命令,使用的就是默认的配置。一般建议将air项目中提供的air_example.toml配置文件复制一份,根据自己的需求做修改和定制:

  1. root = "."
  2. tmp_dir = "tmp"
  3. [build]
  4. cmd = "go build -o ./tmp/main ."
  5. bin = "tmp/main"
  6. full_bin = "APP_ENV=dev APP_USER=air ./tmp/main"
  7. include_ext = ["go", "tpl", "tmpl", "html"]
  8. exclude_dir = ["assets", "tmp", "vendor", "frontend/node_modules"]
  9. include_dir = []
  10. exclude_file = []
  11. log = "air.log"
  12. delay = 1000 # ms
  13. stop_on_error = true
  14. send_interrupt = false
  15. kill_delay = 500 # ms
  16. [log]
  17. time = false
  18. [color]
  19. main = "magenta"
  20. watcher = "cyan"
  21. build = "yellow"
  22. runner = "green"
  23. [misc]
  24. clean_on_exit = true

可以配置项目根目录,临时文件目录,编译和执行的命令,监听文件目录,监听后缀名,甚至控制台日志颜色都可以配置。

调试模式

如果想查看air更详细的执行流程,可以使用-d选项。

每日一库之56:air - 图3

使用-d选项,air会输出非常详细的信息,可以帮助排查问题。

总结

在开发期,使用air可以避免频繁地编译,重启。把这些都自动化了,大大地提升了开发效率。

大家如果发现好玩、好用的 Go 语言库,欢迎到 Go 每日一库 GitHub 上提交 issue😄

参考

  1. air GitHub:https://github.com/cosmtrek/air
  2. Go 每日一库 GitHub:https://github.com/go-quiz/go-daily-lib