Go 每日一库之 air

简介

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

快速使用

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

先建立目录并初始化:git

$ mkdir air && cd air
$ go mod init github.com/darjun/go-daily-lib/air

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

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

上面的命令会在$GOPATH/bin目录下生成air命令。我通常会将$GOPATH/bin加入系统PATH中,因此能够方便地在任何地方执行air命令。golang

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

package main

import (
  "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编译,而后重启。frontend

使用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 # ms
stop_on_error = true
send_interrupt = false
kill_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😄

参考

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

个人博客:https://darjun.github.io

欢迎关注个人微信公众号【GoUpUp】,共同窗习,一块儿进步~

相关文章
相关标签/搜索