寫Go項目有兩件很煩的事情?本文討論其中之一
寫 Golang 項目有兩件很煩的事情:一件是錯誤處理時連綿不絕的「if err != nil」,另一件是作為編譯型語言,代碼修改后不能實時看到效果,
借助一些工具可以實現文件修改后自動編譯重啟,比如:
- Linux 環境:inotify-tools[1](Golang Automatic Reloads[2])
- Mac 環境:fswatch[3]
不過常見的工具要么不跨平臺,要么操作復雜,好在我發現了一個 facebook 出品的神器:watchman[4],不僅跨平臺,而且操作簡單,你只要寫個腳本對接上就行了,當項目代碼改變時,它會自動調用你的腳本。
- watchman watch[5] /path/to/your/project
- watchman — trigger[6] /path/to/your/project -p '\.go$' — /path/to/your/script
注意:如果遇到問題可以查日志「/usr/local/var/run/watchman/*-state/log」
注意:如果你的編輯器有自動保存之類的功能,務必記得關閉它,比如 vscode:

自動保存
除了 watch 之外,還有一些別的選擇,比如 air[7] 也不錯,這里有一篇介紹文章:Go開發過程中總是要停下來編譯:用它解決你的煩惱,快樂編程。
參考資料
- [1].inotify-tools: https://github.com/inotify-tools/inotify-tools
- [2].Golang Automatic Reloads: https://www.alexedwards.net/blog/golang-automatic-reloads
- [3].fswatch: https://github.com/emcrisostomo/fswatch
- [4].watchman: https://facebook.github.io/watchman/
- [5].watch: https://facebook.github.io/watchman/docs/cmd/watch.html
- [6].trigger: https://facebook.github.io/watchman/docs/cmd/trigger.html
- [7].air: https://github.com/cosmtrek/air