Go 熱重載:使用 Air 改變你的開發流程
在 Go 語言開發中,每次修改代碼後都需要手動重啓服務,這無疑是一件效率低下的事情。本文將介紹一款名爲 Air 的工具,它可以幫助我們實現 Go 代碼的熱重載,從而極大地提升開發效率。
手動重啓的煩惱
假設我們有一個運行中的 Go 程序,例如:
go run main.go
該程序可能使用 fsnotify
來監聽配置文件的變化,例如 config.json
:
{
"db_host": "localhost",
"db_user": "user"
}
當我們修改配置文件時,fsnotify
會檢測到變化並應用新的配置。然而,如果我們修改了代碼本身,就必須手動停止並重啓程序才能使修改生效。這種方式不僅繁瑣,而且效率低下。
Air:Go 熱重載的利器
Air 是一款專門爲 Go 語言設計的熱重載工具,它可以監聽項目文件變化,並在代碼修改後自動重新編譯並重啓程序,從而避免手動操作。
安裝 Air
使用以下命令即可輕鬆安裝 Air:
go get -u github.com/cosmtrek/air
使用 Air
在項目根目錄下創建一個名爲 .air.toml
的配置文件,並添加以下內容:
# .air.toml
# Working directory
root = "."
tmp_dir = "tmp"
[build]
# Just plain old `go build` command. You probably want to add `-o tmp/main`
# to specify the output binary path
cmd = "go build -o ./tmp/main ."
# Binary file to run built project
# .air.toml will be searched in the current directory and up to 5 levels above.
bin = "tmp/main"
# Customize watch patterns.
# For example, exclude all test files from being watched.
[build.args]
-v
# Watch these files or directories for changes.
# It accepts regular expressions.
[watcher]
# When a file changes, it will be rebuilt.
patterns = [
"*.go",
"*.tmpl",
"*.html",
"config/*",
]
# This log file will be rotated based on the value of `log.max_size`
log = "air.log"
# It accepts the unit of data size such as B, KB, MB, GB, etc.
log_max_size = "100MB"
# Optional: Customize success/error message.
[misc]
# The following colors can be used:
# black, red, green, yellow, blue, magenta, cyan, white, default
#
# More color can be found at:
# https://github.com/logrusorgru/aurora
success_msg_color = "green"
error_msg_color = "red"
在上述配置文件中,我們指定了項目的根目錄、構建命令、二進制文件路徑以及需要監聽的文件類型。
運行 Air
在項目根目錄下執行以下命令即可啓動 Air:
air
Air 會啓動程序並在後臺監聽文件變化。當我們修改代碼並保存後,Air 會自動重新編譯並重啓程序,並在控制檯輸出相關信息。
Air 的優勢
使用 Air 進行 Go 熱重載具有以下優勢:
-
提升開發效率: 無需手動重啓服務,代碼修改後立即生效,大大節省開發時間。
-
簡化開發流程: 只需運行 Air,即可自動完成代碼編譯、重啓等操作,降低開發複雜度。
-
易於配置: 通過簡單的配置文件即可定製 Air 的行爲,滿足不同項目的需求。
總結
Air 是一款功能強大的 Go 熱重載工具,它可以幫助我們告別手動重啓服務的煩惱,提高開發效率。如果你正在使用 Go 語言進行開發,強烈推薦嘗試使用 Air 來優化你的開發流程。
本文由 Readfog 進行 AMP 轉碼,版權歸原作者所有。
來源:https://mp.weixin.qq.com/s/Odfu7ni5SMNrExM2tAmJvg