简介
air
是 Go 语言的热加载工具,它能够监听文件或目录的变动,主动编译,重启程序。大大提高开发期的工作效率。
疾速应用
本文代码应用 Go Modules,在 Mac 上运行。
先创立目录并初始化:
$ mkdir air && cd air$ go mod init github.com/darjun/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/darjun/go-daily-lib
我
我的博客:https://darjun.github.io
欢送关注我的微信公众号【GoUpUp】,独特学习,一起提高~