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】,共同窗習,一塊兒進步~

相關文章
相關標籤/搜索