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

写 Go 项目有两件很烦的事情?本文讨论其中之一

写Go项目有两件很烦的事情?本文讨论其中之一_第1张图片

自动保存

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

【编辑推荐】

  1. Golang还是Python?哪种语言更适合AI?
  2. 初学Golang语言需要注意那些坑
  3. 谷歌的语言何以战胜Python?50%的人都应该立即学习Golang
  4. Golang:三个常见的编程问题
  5. 云原生的 Java与Golang

【责任编辑:未丽燕 TEL:(010)68476606】