簡介

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 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

編譯,然後重啟。

使用

air

,我們只需要執行下面的命令就可以執行程式:

$ air

air

會自動編譯,啟動程式,並監聽當前目錄中的檔案修改:

Go 每日一庫之 air

當我們將

Hello, world!

改為

Hello, dj!

時,

air

監聽到了這個修改,會自動編譯,並且重啟程式:

Go 每日一庫之 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

選項。

Go 每日一庫之 air

使用

-d

選項,

air

會輸出非常詳細的資訊,可以幫助排查問題。

總結

在開發期,使用

air

可以避免頻繁地編譯,重啟。把這些都自動化了,大大地提升了開發效率。

大家如果發現好玩、好用的 Go 語言庫,歡迎到 Go 每日一庫 GitHub 上提交 issue

參考

air GitHub:

https://

github。com/cosmtrek/air

Go 每日一庫 GitHub:

https://

github。com/darjun/go-da

ily-lib

我的部落格:https://darjun。github。io

歡迎關注我的微信公眾號【GoUpUp】,共同學習,一起進步~

Go 每日一庫之 air